Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions sites/docs/firebase.json
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@
{ "source": "/platform-integration/android/install-android", "destination": "/platform-integration/android/setup", "type": 301 },
{ "source": "/platform-integration/android/install-android/:rest*", "destination": "/platform-integration/android/setup", "type": 301 },
{ "source": "/platform-integration/android/splash-screen-migration", "destination": "/release/breaking-changes/splash-screen-migration", "type": 301 },
{ "source": "/platform-integration/bind-native-code", "destination": "/interop/bind-native-code", "type": 301 },
{ "source": "/platform-integration/c-interop", "destination": "/platform-integration/legacy-ffi-plugin", "type": 301 },
{ "source": "/platform-integration/ios-app-clip", "destination": "/platform-integration/ios/ios-app-clip", "type": 301 },
{ "source": "/platform-integration/ios/c-interop", "destination": "/platform-integration/legacy-ffi-plugin", "type": 301 },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ Play services runtime on Android, use the standard plugin template (`flutter cre
--template=plugin`).

:::note
Looking for the previous FFI plugin workflow? See
Looking for the previous FFI plugin workflow? Consult
[Bind to native code using the legacy FFI plugin template](/platform-integration/legacy-ffi-plugin),
which documents the `plugin_ffi` template and OS-specific build files.
:::

[build hooks]: https://dart.dev/tools/hooks
[build hooks]: {{site.dart-site}}/tools/hooks
[dart:ffi]: {{site.dart.api}}/dart-ffi/dart-ffi-library.html
[FFI]: https://en.wikipedia.org/wiki/Foreign_function_interface

Expand Down Expand Up @@ -114,9 +114,9 @@ For Windows, you often use `DynamicLoadingSystem()` and provide the name of the
DLL.

:::note
For desktop-specific guidance on calling system APIs—including wrapper
For desktop-specific guidance on calling system APIs—including wrapper
packages like [`package:win32`]({{site.pub-pkg}}/win32) and
[Canonical's Linux packages]({{site.pub}}/publishers/canonical.com/packages)—see
[Canonical's Linux packages]({{site.pub}}/publishers/canonical.com/packages)—refer to
[Integrating with Windows](/platform-integration/windows/building#integrating-with-windows)
and [Integrate with Linux](/platform-integration/linux/building#integrate-with-linux).
:::
Expand Down Expand Up @@ -215,8 +215,8 @@ void main(List<String> args) async {
You would need to handle different architectures and platforms by having
different versions of your pre-compiled library.

For more examples, see the [code_assets package
examples](https://pub.dev/packages/code_assets/example).
To explore additional examples, consult the
[`package:code_assets` examples]({{site.pub-pkg}}/code_assets/example).

## Dynamic library naming guidelines

Expand Down
62 changes: 62 additions & 0 deletions sites/docs/src/content/interop/dart-ffi.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
---
title: Interact with native memory using dart:ffi
shortTitle: dart:ffi
description: >-
Learn how to interact with native memory using the dart:ffi library.
---

The `dart:ffi` (Foreign Function Interface) library is a core Dart SDK library
that provides the low-level APIs to call C-ABI functions from Dart.

Rather than code generation tools like [Pigeon](/interop/pigeon),
[FFIgen](/interop/ffigen),
or [JNIgen](/interop/jnigen),
`dart:ffi` is the underlying technology that powers these tools
and enables native memory interop.

## When to use `dart:ffi` and `package:ffi`

Dart memory is automatically garbage collected while native C memory is
manually managed, so use `dart:ffi` and `package:ffi` to bridge this gap.

The two most common scenarios when `package:ffi` is needed alongside `dart:ffi`
are memory allocation and C string conversion.

With memory allocation, use `package:ffi` to allocate space on the system heap
for native arguments, and manually free that memory when done
to prevent memory leaks.

With data conversion, use `package:ffi` to convert Dart strings into C strings
(`Pointer<Utf8>` or `Pointer<Utf16>`) so they can be read by native C code.

## Core tools: `dart:ffi` and `package:ffi`

To write C interop code, use two libraries:

- **`dart:ffi`:** Built into the core Dart SDK and required for doing FFI
interop. It provides native representation types, pointers, structs, and
function lookup signatures.
- **`package:ffi`:** A companion package that contains utilities helpful in
common C interop use cases, such as memory allocation (`calloc` and `malloc`)
and C string conversion helpers.

## Concurrency in Flutter

FFI calls are synchronous and run on the thread on which they're called.
If you invoke a heavy or blocking C function on your Flutter app's
main UI thread, your app may freeze or drop frames.
To prevent this, execute blocking FFI calls inside a background Dart isolate
using `Isolate.run`.

## Resources

To explore examples of memory allocation, string conversion,
and dynamic library loading, refer to these Dart interop resources:

- [C interop guide (includes code examples for pointers, memory allocation, and structs)][dart-c-interop]
- [`dart:ffi` API reference][dart-ffi-api]
- [`package:ffi` on pub.dev][package-ffi-pub]

[dart-c-interop]: {{site.dart-site}}/interop/c-interop
[dart-ffi-api]: {{site.dart.api}}/dart-ffi/dart-ffi-library.html
[package-ffi-pub]: {{site.pub-pkg}}/ffi
155 changes: 155 additions & 0 deletions sites/docs/src/content/interop/ffigen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
---
title: FFIgen
description: >-
Learn how to use FFIgen to generate type-safe Dart bindings
for C, Objective-C, and Swift APIs.
---

## Overview

FFIgen (the Foreign Function Interface generator) is a code generator tool
that creates type-safe Dart bindings for C libraries and Apple frameworks
(Objective-C and Swift).
This allows calling Apple platform APIs (iOS and macOS) directly
and synchronously from your Dart code.

:::note
Direct Swift interop is in experimental support.
:::
Comment thread
lamek marked this conversation as resolved.
Resolved

## When to use FFIgen

Use FFIgen when you need to call C libraries,
wrap compiled binaries (like C, C++, Rust, or Go),
or interact directly with Objective-C and Swift frameworks on iOS and macOS.

:::note
FFIgen parses C and Objective-C headers.
To wrap C++ libraries, expose a C-compatible interface
around your C++ code.
FFIgen can't parse C++ classes or templates directly.
:::

For standard, cross-platform plugin development where you don't have
critical data transfers, use [Pigeon](/interop/pigeon)
instead.

## Developer flow

Generate bindings with FFIgen using the following steps:

1. Reference the native headers.
1. Write the FFIgen configuration script.
1. Generate the bindings by running FFIgen.
1. Call the generated code from Dart.

To start, identify the native header files or APIs you want to wrap.
Then write a configuration script (typically `tool/ffigen.dart`).
This configuration specifies where the header files are located
and where to output the generated Dart code.

Next, run the configuration script (`dart run tool/ffigen.dart`),
which parses the headers and generates the corresponding Dart bindings.

Last, import the generated Dart file into your app and call the functions
directly.
FFIgen communicates directly through the underlying FFI layer,
so refer to the [`dart:ffi` guide](/interop/dart-ffi)
to learn how to manage native memory lifetimes and execute native calls
without blocking the UI thread.

:::note
If the native API changes, update your configuration script
and regenerate the bindings.
:::

## Example
Comment thread
lamek marked this conversation as resolved.
Resolved

To explore a complete implementation of this flow,
including how to configure the generator,
refer to the [official FFIgen examples][ffigen-examples].

The `add` example highlights the general flow with a toy native API
(one function in a single header file).

The `code_assets` examples highlight real-world examples like
system hostname lookups and audio playback.

For a production package on pub.dev that uses FFIgen to wrap Apple's
`NSURLSession` API, check out [`package:cupertino_http`][cupertino-http-pub]
([source on GitHub][cupertino-http-src]).

## Constraints and limitations

Some general considerations when working with FFIgen:

### Source header files

FFIgen uses `libclang` to parse headers.
Always resolve compiler warnings logged during generation
to prevent runtime crashes.

### OS differences

Dart has no equivalent of C macros (like `#if TARGET_OS_IPHONE`),
so handle minor API variations using runtime `Platform.isIOS` checks.

Some Objective-C and Swift-specific pitfalls when working with FFIgen:

### Objective-C bindings

Objective-C methods are dynamically resolved.
FFIgen automatically maps method selectors to Dart signatures,
but verify selectors by reading the bindings
if you're using heavily overloaded native methods.

### Objective-C memory management

Dart uses garbage collection while Objective-C uses reference counting.
Passing Dart closures that close over native wrapper objects can easily create
reference cycles and leak memory.
Comment thread
lamek marked this conversation as resolved.
Resolved
To break these reference cycles, wrap the captured object in a `WeakReference`,
as shown in the [Objective-C memory management guide][objc-gc-doc].

### Objective-C runtime checks

FFIgen wrappers enforce Dart static types,
but the underlying Objective-C object might have a different runtime subclass,
so Dart's `is` and `as` keywords won't work as expected.
Use `.isA()` and `.as()` instead, as shown in the
[Objective-C runtime types guide][objc-runtime-types-doc].

### Objective-C multithreading

UI-related Objective-C calls must run on the iOS main platform thread.
Also, some types of callbacks can crash your app
if they're executed on the wrong thread.
Comment thread
lamek marked this conversation as resolved.
Resolved
To learn more, consult the [Objective-C threading guide][objc-threading-doc].

### Swift compatibility

FFIgen interacts with Swift through Objective-C.
Pure Swift features (such as structs, generics, or enums associated with values)
aren't supported, and classes must be annotated with `@objc`.
For pure Swift interop, explore the Dart team's experimental
[`package:swiftgen`][swiftgen-pub] package,
or use [Pigeon](/interop/pigeon) for production Swift plugins.

## Resources

To learn about generating C, Objective-C, and Swift bindings with FFIgen,
refer to the following resources:

- [FFIgen package on pub.dev][ffigen-pub]
- [`objective_c` package on pub.dev][objc-pub]
- [Official FFIgen examples on GitHub][ffigen-examples]

[ffigen-pub]: {{site.pub-pkg}}/ffigen
[objc-pub]: {{site.pub-pkg}}/objective_c
[swiftgen-pub]: {{site.pub-pkg}}/swiftgen
[cupertino-http-pub]: {{site.pub-pkg}}/cupertino_http
[cupertino-http-src]: https://github.com/dart-lang/http/tree/master/pkgs/cupertino_http
[ffigen-examples]: https://github.com/dart-lang/native/tree/main/pkgs/ffigen/example
[objc-gc-doc]: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/doc/objc_gc.md
[objc-runtime-types-doc]: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/doc/objc_runtime_types.md
[objc-threading-doc]: https://github.com/dart-lang/native/blob/main/pkgs/ffigen/doc/objc_threading.md
Loading
Loading