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 fileDescription
    hello.dartA 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.cA 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:

    1. Import dart:ffi.
    2. Create a typedef for the variable that you’ll use when calling the C function.
    3. Open the dynamic library that contains the C function.
    4. Get a reference to the C function, and put it into a variable.
    5. Call the C function.

    Here’s the code for each step.

    1. Import dart:ffi.

      1. import 'dart:ffi' as ffi;
    2. Open the dynamic library that contains the C function.

    3. 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.

      1. final HelloWorld hello = dylib
      2. .lookup<ffi.NativeFunction<hello_world_func>>('hello_world')
      3. .asFunction();
    4. Call the C function.

    Once you understand the hello_world example, you should be ready to look at the other dart:ffi examples.