C interop using dart:ffi
As of Dart 2.7, dart:ffi is in beta, and breaking API changes might still happen. If you’re developing a Flutter app, you can get access to dart:ffi by using the Flutter dev channel, as described in the
API documentation is available from the dev channel: dart:ffi API reference.
The following examples show how to use the dart:ffi library:
The has the minimum necessary code for calling a C library.
The hello_world example has the following files:
Source file | Description |
hello.dart | A Dart file that uses the function from a C library. |
The usual Dart pubspec, with a lower bounds on the SDK that’s at least 2.5. | |
Declares the hello_world() function. | |
hello_library/hello.c | A C file that imports hello.h and defines the hello_world() function. |
A CMake build file for compiling the C code into a dynamic library. |
Here’s an example of building the dynamic library and executing the Dart app:
On macOS, the Dart VM () can load only signed libraries. For details and workarounds, see SDK issue #38314.
The illustrates the steps for using dart:ffi to call a C function:
- Import dart:ffi.
- Create a typedef for the variable that you’ll use when calling the C function.
- Open the dynamic library that contains the C function.
- Get a reference to the C function, and put it into a variable.
- Call the C function.
Here’s the code for each step.
Import dart:ffi.
import 'dart:ffi' as ffi;
Open the dynamic library that contains the C function.
Get a reference to the C function, and put it into a variable. This code uses the typedefs defined in steps 2 and 3, along with the dynamic library variable from step 4.
final HelloWorld hello = dylib
.lookup<ffi.NativeFunction<hello_world_func>>('hello_world')
.asFunction();
Call the C function.
Once you understand the hello_world example, you should be ready to look at the other dart:ffi examples.