You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 9316bf0
Browse filesBrowse the repository at this point in the historyBrowse files
[pigeon] Fix JNI/FFI typed data memory lifetime bugs and update docs (flutter#13061)
Fixesflutter#193465
**JNI (Android):** `JArray.getRange` returns a typed list backed by `malloc`'d
memory whose finalizer runs when the isolate that created it exits. If a
Pigeon call was made in `Isolate.run`, the returned `Int64List`/`Float64List`/etc.
was freed as soon as the result was sent back, so the receiving isolate read
garbage. The generated codec now copies these into Dart-heap typed lists.
**FFI (iOS/macOS):** When reading `PigeonTypedData`, the `NSData` that owns the
bytes could become unreachable (and be released by its finalizer) while
`fromList` was still copying from its buffer. The generated code now uses `data`
after the copy so it stays alive, and returns empty lists directly for empty
data instead of calling `asTypedList` on a possibly-null pointer.
The JNI fix adds one copy per array. Removing it would need `package:jni` to
fill Dart-heap lists directly; that's better done upstream.
## Pre-Review Checklist
- [] I read the [Contributor Guide] and followed the process outlined there for submitting PRs.
**Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed.
[^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
Copy file name to clipboardExpand all lines: packages/pigeon/native_interop_guide.md
+26-18Lines changed: 26 additions & 18 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -46,12 +46,8 @@ Using Native Interop in pigeon follows the standard pigeon workflow, with a few
46
46
To use Native Interop, your development environment and the corresponding external tools must be configured:
47
47
48
48
### Android (JNI / JNIgen)
49
-
-**Java 17**: Required specifically by the Android build tools and JNIgen.
50
-
-**Android SDK**: Must be installed and configured in your path.
51
-
-**Kotlin Version (`<= 2.1.0`)**: JNIgen uses `kotlinx-metadata-jvm` to parse Kotlin class metadata. It currently supports Kotlin metadata versions up to **2.1.0**. If the Android Gradle project uses a higher Kotlin plugin version (e.g. Kotlin 2.4.0), JNIgen will throw `IllegalArgumentException: Provided Metadata instance has version ... while maximum supported version is ...`. Ensure `settings.gradle.kts` sets Kotlin to `2.1.0`:
52
-
```kotlin
53
-
id("org.jetbrains.kotlin.android") version "2.1.0" apply false
54
-
```
49
+
-**Android SDK**: Must be installed and configured in your path. JNIgen uses the JDK bundled with Flutter by default, so a separate JDK installation is not required.
50
+
-**`jnigen` 1.0.0 or later**: Earlier versions of JNIgen cannot parse metadata from newer Kotlin compilers and fail with `IllegalArgumentException: Provided Metadata instance has version ... while maximum supported version is ...`. `jnigen` 1.0.0 supports Kotlin metadata up to 2.4.
55
51
56
52
### iOS/macOS (FFI / FFIgen)
57
53
-**LLVM (version 9+) / Xcode Command Line Tools**: Required by FFIgen to parse C/Objective-C headers (`xcode-select --install`).
@@ -62,24 +58,27 @@ To use Native Interop, your development environment and the corresponding extern
62
58
63
59
### Step 1: Add Dependencies
64
60
65
-
Add the required runtime dependencies to `dependencies` and code generators to `dev_dependencies`. Using `flutter pub add` ensures runtime packages resolve to the latest compatible versions:
61
+
Add the required runtime dependencies to `dependencies` and code generators/config-script dependencies to `dev_dependencies` in the package where Pigeon runs (for a plugin package, add these to the **plugin's**`pubspec.yaml`, not `example/pubspec.yaml`, unless the example app runs Pigeon directly).
62
+
63
+
Because Pigeon generates helper scripts in `tool/pigeon/` (`*_ffigen_config.dart` and `*_jnigen_config.dart`), `dart pub publish --dry-run` requires every package imported by `lib/` or `tool/` to be explicitly declared in `pubspec.yaml`:
66
64
67
65
```bash
68
66
# Add Pigeon:
69
67
flutter pub add dev:pigeon
70
68
71
69
# For iOS/macOS Swift FFI:
72
-
flutter pub add ffi
73
-
flutter pub add objective_c
74
-
# Pigeon requires this specific version for compatibility with its generated FFIgen configuration:
#Pigeon requires this specific version for compatibility with its generated JNIgen configuration:
80
-
flutter pub add dev:jnigen@1.0.0
76
+
#Code generator and packages imported by tool/pigeon/*_jnigen_config.dart:
77
+
flutter pub add dev:jnigen dev:logging dev:path
81
78
```
82
79
80
+
*Note: Ensure the resolved `objective_c` version in `pubspec.yaml` matches the version expected by your `ffigen` version (e.g., `ffigen: ^22.0.0` generates bindings that require `objective_c: ^9.6.0`).*
81
+
83
82
### Step 2: Configure Pigeon Options
84
83
85
84
Enable Native Interop for your target platforms by setting the configuration options in your Pigeon file:
@@ -133,11 +132,11 @@ dart run pigeon --input <path/to/pigeon_file.dart>
133
132
When Native Interop options (`useJni` or `useFfi`) are enabled, Pigeon automatically orchestrates running `jnigen` and `ffigen` as part of the generation process:
134
133
135
134
-**Android (JNI)**: When `kotlinOptions.useJni` is enabled:
136
-
1. Generates the JNI-compatible Kotlin bridge and the `jnigen_config.dart` script in `tool/pigeon/`.
135
+
1. Generates the JNI-compatible Kotlin bridge and the `<input_name>_jnigen_config.dart` script in `tool/pigeon/`.
137
136
2. Runs `jnigen` via the config script to parse the Kotlin bridge and produce Dart JNI bindings.
138
137
3. Generates the final pigeon Dart output that wraps and imports those JNI bindings.
139
138
-**iOS/macOS (FFI)**: When `swiftOptions.useFfi` is enabled:
140
-
1. Generates the Objective-C compatible Swift bridge and the `ffigen_config.dart` script in `tool/pigeon/`.
139
+
1. Generates the Objective-C compatible Swift bridge and the `<input_name>_ffigen_config.dart` script in `tool/pigeon/`.
141
140
2. Runs `ffigen` via the config script to parse the Objective-C bridge and produce Dart FFI bindings.
142
141
3. Generates the final pigeon Dart output that wraps and imports those FFI bindings.
143
142
@@ -231,15 +230,15 @@ For standalone Flutter Applications, JNIgen defaults to searching `build/app/tmp
231
230
232
231
### 5.3 Manual Configuration Script Execution
233
232
234
-
Pigeon writes the interop configuration scripts to `tool/pigeon/jnigen_config.dart` and `tool/pigeon/ffigen_config.dart`.
233
+
Pigeon writes the interop configuration scripts to `tool/pigeon/<input_name>_jnigen_config.dart` and `tool/pigeon/<input_name>_ffigen_config.dart`.
235
234
236
235
-**Solution**: Run the generated config scripts directly to view verbose stderr logs and diagnose toolchain errors:
237
236
```bash
238
237
# Debug JNIgen (Android):
239
-
dart run tool/pigeon/jnigen_config.dart
238
+
dart run tool/pigeon/<input_name>_jnigen_config.dart
240
239
241
240
# Debug FFIgen (iOS/macOS):
242
-
dart run tool/pigeon/ffigen_config.dart
241
+
dart run tool/pigeon/<input_name>_ffigen_config.dart
243
242
```
244
243
245
244
### 5.4 Failed to Load Objective-C Class (`<ffiModuleName>.<Api>Setup`)
@@ -248,6 +247,15 @@ If your app crashes at startup with `FailedToLoadClassException: Failed to load
248
247
-**Module Name Mismatch**: Ensure `ffiModuleName` matches your app's Swift module name. If iOS and macOS share the same generated Dart FFI file, ensure both platforms use the same module name (e.g., align macOS by setting `PRODUCT_MODULE_NAME` in `macos/Runner/Configs/AppInfo.xcconfig`).
249
248
-**Linker Dead-Code Stripping**: Ensure your native host code instantiates and registers the implementation (e.g. `MyApiSetup.register(api: api)` in `MainFlutterWindow.swift` on macOS or `AppDelegate.swift` on iOS) so the linker does not strip the class.
250
249
250
+
### 5.5 Startup Crash on Android (`VmServiceDisappearedException` / `JNI is not initialized`)
251
+
252
+
If your app or integration test crashes at startup on Android with `adb logcat` showing:
253
+
```text
254
+
F DartJNI : JNI is not initialized. Are you trying to invoke a Java API from Dart code too early, before 'main()' (such as during Dart plugin class registration)?
255
+
```
256
+
-**Cause**: Your plugin's `registerWith()` method (invoked by Flutter's `_PluginRegistrant.register()` before `main()`) constructed your Dart plugin class, and its constructor eagerly called `<MyApi>.createWithNativeInteropApi()` before `JniPlugin` initialized `DartJNI`.
257
+
-**Solution**: Initialize `<MyApi>.createWithNativeInteropApi()` lazily using `late final` rather than eagerly in the constructor initializer list (see [Section 4 of the Migration Guide](./native_interop_migration_guide.md#4-dart-client-adaptation)).
0 commit comments