dart:ffi
suggest changedart:ffi (foreign function interface) lets Dart code call functions in native C libraries and lets C code call back into Dart. You use it to reuse an existing C library (SQLite, libsodium, a codec), to call operating system APIs that have no Dart wrapper, or to move a hot loop into C.
FFI works on the Dart VM and in AOT-compiled executables (dart compile exe, Flutter mobile and desktop). It is not available on the web; for that see Dart-JavaScript interoperability.
The pieces involved:
dart:ffi(in the SDK):DynamicLibrary,Pointer<T>, native types likeInt32andDouble,Struct,NativeCallable,NativeFinalizer.- package:ffi: allocators (
malloc,calloc,Arena) and UTF-8/UTF-16 string helpers. - A native library: a
.dllon Windows,.soon Linux,.dylibon macOS.
FFI is unsafe in the same way C is: a wrong signature, a dangling pointer or a missing free crashes the process or leaks memory, and the Dart type system can't save you.
The C library used in this article
All examples call into this small library. It is plain C with no dependencies besides the C runtime:
// native.c
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#if defined(_WIN32)
#include <windows.h>
#define EXPORT __declspec(dllexport)
#else
#include <pthread.h>
#include <unistd.h>
#define EXPORT __attribute__((visibility("default")))
#endif
EXPORT int32_t add(int32_t a, int32_t b) { return a + b; }
EXPORT double average(const double *values, int32_t count) {
double sum = 0;
for (int32_t i = 0; i < count; i++) sum += values[i];
return count > 0 ? sum / count : 0;
}
EXPORT void fill_squares(int32_t *out, int32_t count) {
for (int32_t i = 0; i < count; i++) out[i] = i * i;
}
EXPORT int32_t count_vowels(const char *s) {
int32_t n = 0;
for (; *s; s++) {
if (strchr("aeiouAEIOU", *s)) n++;
}
return n;
}
// Returns a newly allocated string; caller must release it with free_string.
EXPORT char *to_upper(const char *s) {
size_t len = strlen(s);
char *res = malloc(len + 1);
for (size_t i = 0; i <= len; i++) res[i] = (char)toupper((unsigned char)s[i]);
return res;
}
EXPORT void free_string(char *s) { free(s); }
typedef struct {
double x;
double y;
} Point;
EXPORT double distance(Point a, Point b) {
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
EXPORT void translate(Point *p, double dx, double dy) {
p->x += dx;
p->y += dy;
}
EXPORT Point midpoint(Point a, Point b) {
Point m = {(a.x + b.x) / 2, (a.y + b.y) / 2};
return m;
}
// Synchronous callback: simple insertion sort using a caller-supplied comparator.
typedef int32_t (*compare_fn)(int32_t a, int32_t b);
EXPORT void sort_ints(int32_t *arr, int32_t n, compare_fn cmp) {
for (int32_t i = 1; i < n; i++) {
int32_t v = arr[i], j = i - 1;
while (j >= 0 && cmp(arr[j], v) > 0) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = v;
}
}
// Opaque handle with explicit lifetime.
typedef struct Counter {
int64_t value;
} Counter;
EXPORT Counter *counter_new(int64_t start) {
Counter *c = malloc(sizeof(Counter));
c->value = start;
return c;
}
EXPORT void counter_increment(Counter *c) { c->value++; }
EXPORT int64_t counter_value(Counter *c) { return c->value; }
EXPORT void counter_free(Counter *c) { free(c); }
// Asynchronous callback: invoked from a background thread.
typedef void (*progress_fn)(int32_t percent);
static progress_fn g_progress;
#if defined(_WIN32)
static DWORD WINAPI worker(LPVOID arg) {
#else
static void *worker(void *arg) {
#endif
for (int32_t p = 25; p <= 100; p += 25) {
#if defined(_WIN32)
Sleep(50);
#else
usleep(50 * 1000);
#endif
g_progress(p);
}
return 0;
}
EXPORT void start_work(progress_fn cb) {
g_progress = cb;
#if defined(_WIN32)
HANDLE h = CreateThread(NULL, 0, worker, NULL, 0, NULL);
CloseHandle(h);
#else
pthread_t t;
pthread_create(&t, NULL, worker, NULL);
pthread_detach(t);
#endif
}
Build it as a shared library and put it in the directory you run dart from:
# Windows (clang from LLVM or Visual Studio)
clang -shared -O2 -o native.dll native.c
# Linux
clang -shared -fPIC -O2 -o libnative.so native.c -lm -lpthread
# macOS
clang -shared -O2 -o libnative.dylib native.c
The examples live in a Dart console project with package:ffi added:
dart create -t console ffi_demo
cd ffi_demo
dart pub add ffi
The output shown was produced on Windows. To keep them short, examples after the first open native.dll directly; use the platform switch from the first example for portable code.
Loading a library and calling a function
Every native function needs two signatures:
- The native signature uses
dart:ffitypes (Int32,Double,Pointer<Utf8>,Void) that describe the exact C ABI. - The Dart signature uses ordinary Dart types (
int,double,void) that your code calls.
DynamicLibrary.open loads the library, lookup finds a symbol and asFunction turns it into a callable Dart function. lookupFunction combines the last two:
import 'dart:ffi';
import 'dart:io';
// C signature: int32_t add(int32_t a, int32_t b);
typedef AddNative = Int32 Function(Int32 a, Int32 b);
typedef AddDart = int Function(int a, int b);
DynamicLibrary openNative() {
if (Platform.isWindows) return DynamicLibrary.open('native.dll');
if (Platform.isMacOS) return DynamicLibrary.open('libnative.dylib');
return DynamicLibrary.open('libnative.so');
}
void main() {
final lib = openNative();
// Long form: look up a Pointer<NativeFunction>, then convert it.
final addPtr = lib.lookup<NativeFunction<AddNative>>('add');
final AddDart add = addPtr.asFunction<AddDart>();
print(add(2, 3));
// Short form: lookupFunction does both steps.
final add2 = lib.lookupFunction<AddNative, AddDart>('add');
print(add2(40, 2));
// Int32 wraps around just like in C.
print(add(2147483647, 1));
print(lib.providesSymbol('add'));
print(lib.providesSymbol('subtract'));
}
Output:
5
42
-2147483648
true
false
The native integer types fix the width: Int8 to Int64, Uint8 to Uint64, plus ABI-dependent Int, Long, Size and IntPtr that match the C types on the current platform. All of them map to Dart int. Float and Double map to double, Bool to bool. As the third call shows, values are truncated to the native width without any error.
The two signatures must agree: an Int32 must be paired with int, a Double with double. Mismatches are compile errors. What the compiler can't check is that the native signature matches the actual C function, so copy it carefully from the header.
Calling system libraries
The same mechanism works for any library already on the system. Here we ask the OS for the process id and compare it with pid from dart:io:
import 'dart:ffi';
import 'dart:io';
// Windows: DWORD GetCurrentProcessId(void) in kernel32.dll
// Linux/macOS: pid_t getpid(void) in the C library
void main() {
final int Function() getPid;
if (Platform.isWindows) {
final kernel32 = DynamicLibrary.open('kernel32.dll');
getPid = kernel32
.lookupFunction<Uint32 Function(), int Function()>('GetCurrentProcessId');
} else {
// Symbols of the C library are already loaded into the process.
getPid = DynamicLibrary.process()
.lookupFunction<Int32 Function(), int Function()>('getpid');
}
print(getPid() == pid);
}
Output:
true
DynamicLibrary.process() gives access to symbols already loaded in the process (on Linux and macOS this includes libc). DynamicLibrary.executable() looks only at the main executable, which is useful for AOT executables that statically link C code.
Pointers and native memory
Native memory is not managed by Dart's garbage collector. You allocate it with an allocator from package:ffi and must free it with the same allocator:
malloc<T>(count): uninitialized memory, like Cmalloc.calloc<T>(count): zero-filled memory, like Ccalloc.
A Pointer<T> is a typed address. Use .value for a single element, [i] for array indexing and .asTypedList(n) to get a typed data view backed by the native memory:
import 'dart:ffi';
import 'dart:typed_data';
import 'package:ffi/ffi.dart';
final lib = DynamicLibrary.open('native.dll');
final average = lib.lookupFunction<
Double Function(Pointer<Double>, Int32),
double Function(Pointer<Double>, int)>('average');
final fillSquares = lib.lookupFunction<
Void Function(Pointer<Int32>, Int32),
void Function(Pointer<Int32>, int)>('fill_squares');
void main() {
// Allocate a single value and read/write it through .value.
final p = calloc<Int64>();
p.value = 1234;
print('value: ${p.value}, address: 0x${p.address.toRadixString(16)}');
calloc.free(p);
// Copy a Dart list into native memory and pass it to C.
final values = [1.5, 2.5, 3.0, 9.0];
final buf = malloc<Double>(values.length);
for (var i = 0; i < values.length; i++) {
buf[i] = values[i];
}
print('average: ${average(buf, values.length)}');
malloc.free(buf);
// Let C fill a buffer, then view it as a typed list without copying.
const n = 6;
final out = calloc<Int32>(n);
fillSquares(out, n);
final Int32List view = out.asTypedList(n);
print('squares: $view');
print('copy: ${List<int>.of(view)}');
calloc.free(out); // view must not be used after this
}
Output (the address differs on every run):
value: 1234, address: 0x22dccd7ef60
average: 4.0
squares: [0, 1, 4, 9, 16, 25]
copy: [0, 1, 4, 9, 16, 25]
asTypedList does not copy: the Int32List reads and writes the native buffer directly. That makes it fast, but the view becomes a dangling reference once the memory is freed, so copy the data out (as with List<int>.of) if you need it later. You can also pass a finalizer: argument to asTypedList to free the memory when the list is garbage collected.
nullptr is the null pointer; compare against it before dereferencing a pointer returned from C. p.cast<U>() reinterprets a pointer as a different type, p + n advances by n elements and sizeOf<T>() returns the size of a native type in bytes.
Strings
C strings are NUL-terminated byte arrays, while Dart strings are UTF-16. package:ffi provides the Utf8 type and two conversions:
String.toNativeUtf8()allocates a NUL-terminated UTF-8 copy and returns aPointer<Utf8>. By default it usesmalloc.Pointer<Utf8>.toDartString()decodes a C string into a DartString.
Freeing is the tricky part. Memory you allocated is freed with your allocator. Memory allocated by C must be freed by the C library, because Dart's malloc may not use the same heap as the library (a real problem on Windows, where each DLL can link its own C runtime). That's why native.c exports free_string:
import 'dart:ffi';
import 'package:ffi/ffi.dart';
final lib = DynamicLibrary.open('native.dll');
final countVowels = lib.lookupFunction<
Int32 Function(Pointer<Utf8>),
int Function(Pointer<Utf8>)>('count_vowels');
final toUpper = lib.lookupFunction<
Pointer<Utf8> Function(Pointer<Utf8>),
Pointer<Utf8> Function(Pointer<Utf8>)>('to_upper');
final freeString = lib.lookupFunction<
Void Function(Pointer<Utf8>),
void Function(Pointer<Utf8>)>('free_string');
String upper(String s) {
final input = s.toNativeUtf8(); // malloc'd, NUL-terminated UTF-8 copy
final result = toUpper(input);
try {
return result.toDartString();
} finally {
malloc.free(input); // we allocated it, we free it
freeString(result); // C allocated it, C frees it
}
}
void main() {
final s = 'Hello from Dart'.toNativeUtf8();
print(countVowels(s));
print(s.length); // bytes, not counting the NUL terminator
malloc.free(s);
print(upper('dart:ffi is fun'));
// using() frees everything allocated from the arena when the callback ends.
final n = using((Arena arena) {
final a = 'banana'.toNativeUtf8(allocator: arena);
final b = 'queueing'.toNativeUtf8(allocator: arena);
final c = 'żółw'.toNativeUtf8(allocator: arena);
print('żółw: ${'żółw'.length} UTF-16 code units, ${c.length} UTF-8 bytes');
return countVowels(a) + countVowels(b);
});
print(n);
}
Output:
4
15
DART:FFI IS FUN
żółw: 4 UTF-16 code units, 7 UTF-8 bytes
8
using creates an Arena, an allocator that remembers every allocation and frees them all when the callback returns or throws. It removes most of the try/finally boilerplate when a call needs several temporary buffers.
Pointer<Utf8>.length counts bytes, which differs from String.length for non-ASCII text. For Windows APIs that take wchar_t* strings, use Utf16 and toNativeUtf16() instead.
Structs
A C struct is mirrored by a final class that extends Struct. Each field is declared external and annotated with its native type. Dart computes the same layout (field offsets, padding, alignment) a C compiler would:
import 'dart:ffi';
import 'package:ffi/ffi.dart';
// Mirrors: typedef struct { double x; double y; } Point;
final class Point extends Struct {
@Double()
external double x;
@Double()
external double y;
@override
String toString() => 'Point($x, $y)';
}
final lib = DynamicLibrary.open('native.dll');
final distance = lib.lookupFunction<
Double Function(Point, Point),
double Function(Point, Point)>('distance');
final midpoint = lib.lookupFunction<
Point Function(Point, Point),
Point Function(Point, Point)>('midpoint');
final translate = lib.lookupFunction<
Void Function(Pointer<Point>, Double, Double),
void Function(Pointer<Point>, double, double)>('translate');
void main() {
print('sizeOf<Point>() = ${sizeOf<Point>()}');
// Structs in native memory, accessed through .ref
final a = calloc<Point>();
final b = calloc<Point>();
a.ref
..x = 0
..y = 0;
b.ref
..x = 3
..y = 4;
// Passing by value copies the struct.
print(distance(a.ref, b.ref));
// A struct returned by value lives in Dart-managed memory.
final m = midpoint(a.ref, b.ref);
print(m);
// Passing a pointer lets C modify our struct.
translate(b, 10, -1);
print(b.ref);
calloc.free(a);
calloc.free(b);
// Struct.create() allocates in Dart memory, no free needed (Dart 3.4+).
final p = Struct.create<Point>()
..x = 1
..y = 1;
final q = Struct.create<Point>()
..x = 4
..y = 5;
print(distance(p, q));
}
Output:
sizeOf<Point>() = 16
5.0
Point(1.5, 2.0)
Point(13.0, 3.0)
5.0
There are three ways to get a struct:
calloc<Point>()allocates it in native memory and returnsPointer<Point>. Fields are accessed through.ref, and you must free it.- A struct returned by value from C is copied into Dart-managed memory.
Struct.create<Point>()creates one in Dart memory. It is garbage collected and can be passed by value, but you can't take a pointer to it.
Use Pointer<Point> in the native signature when C takes Point*, and Point when C takes the struct by value.
Arrays, packing and unions
Fixed-size arrays inside a struct use @Array(n) with Array<T>. @Packed(1) matches #pragma pack(1), and a class extending Union mirrors a C union:
import 'dart:ffi';
// struct Header { uint8_t tag; uint32_t length; char name[8]; };
final class Header extends Struct {
@Uint8()
external int tag;
@Uint32()
external int length;
@Array(8)
external Array<Uint8> name;
}
// Same fields without padding: #pragma pack(1)
@Packed(1)
final class PackedHeader extends Struct {
@Uint8()
external int tag;
@Uint32()
external int length;
@Array(8)
external Array<Uint8> name;
}
// union Value { int64_t i; double d; };
final class Value extends Union {
@Int64()
external int i;
@Double()
external double d;
}
void main() {
print('Header: ${sizeOf<Header>()} bytes');
print('PackedHeader: ${sizeOf<PackedHeader>()} bytes');
print('Value: ${sizeOf<Value>()} bytes');
final h = Struct.create<Header>();
final name = 'dart'.codeUnits;
for (var i = 0; i < name.length; i++) {
h.name[i] = name[i];
}
print(String.fromCharCodes([for (var i = 0; i < 8; i++) h.name[i]]
.takeWhile((c) => c != 0)));
final v = Union.create<Value>();
v.d = 1.0;
print('0x${v.i.toRadixString(16)}'); // IEEE 754 bits of 1.0
}
Output:
Header: 16 bytes
PackedHeader: 13 bytes
Value: 8 bytes
dart
0x3ff0000000000000
Header is 16 bytes because the C ABI inserts 3 bytes of padding after tag to align length to 4 bytes. Getting this right automatically is why you should declare structs in Dart instead of reading raw bytes at hand-computed offsets.
For a type whose fields you don't need to see, such as a handle returned by a library, extend Opaque and only use it through a Pointer (shown in the finalizer section below).
Callbacks from C to Dart
Many C APIs take a function pointer. To pass a Dart function you need a Pointer<NativeFunction<T>> that C can call:
import 'dart:ffi';
import 'package:ffi/ffi.dart';
typedef CompareNative = Int32 Function(Int32 a, Int32 b);
final lib = DynamicLibrary.open('native.dll');
final sortInts = lib.lookupFunction<
Void Function(Pointer<Int32>, Int32, Pointer<NativeFunction<CompareNative>>),
void Function(Pointer<Int32>, int, Pointer<NativeFunction<CompareNative>>)>(
'sort_ints',
);
// Must be a top-level or static function for Pointer.fromFunction.
int descending(int a, int b) => b - a;
void sortWith(List<int> values, Pointer<NativeFunction<CompareNative>> cmp) {
final buf = calloc<Int32>(values.length);
buf.asTypedList(values.length).setAll(0, values);
sortInts(buf, values.length, cmp);
print(buf.asTypedList(values.length));
calloc.free(buf);
}
void main() {
final data = [5, 3, 9, 1, 7];
// 1. Pointer.fromFunction: static function, exceptionalReturn is
// what C gets if the Dart function throws.
final descPtr = Pointer.fromFunction<CompareNative>(descending, 0);
sortWith(data, descPtr);
// 2. NativeCallable.isolateLocal: works with closures too.
var calls = 0;
final ascending = NativeCallable<CompareNative>.isolateLocal(
(int a, int b) {
calls++;
return a - b;
},
exceptionalReturn: 0,
);
sortWith(data, ascending.nativeFunction);
print('comparator called $calls times');
ascending.close(); // release the native trampoline
}
Output:
[9, 7, 5, 3, 1]
[1, 3, 5, 7, 9]
comparator called 7 times
Pointer.fromFunctionworks only with top-level or static functions and returns a pointer that stays valid forever.NativeCallable.isolateLocalalso accepts closures that capture state, likecallsabove. Callclose()once C no longer needs it, otherwise it keeps the closure alive.
The exceptionalReturn value is returned to C if the Dart callback throws, because an exception can't propagate through C stack frames. It is required for callbacks that return a value, and for Pointer.fromFunction it must be a constant.
Both kinds of callback must be invoked on the thread running the isolate, while the C function that received the pointer is executing. Calling them from another thread terminates the process.
Callbacks from other threads
C libraries that do work in background threads (network clients, audio, file watchers) call back from a thread Dart doesn't own. For that use NativeCallable.listener. The callback must return void; when C invokes it, the call is queued as a message and the Dart function runs later on the isolate's event loop:
import 'dart:async';
import 'dart:ffi';
typedef ProgressNative = Void Function(Int32 percent);
final lib = DynamicLibrary.open('native.dll');
final startWork = lib.lookupFunction<
Void Function(Pointer<NativeFunction<ProgressNative>>),
void Function(Pointer<NativeFunction<ProgressNative>>)>('start_work');
Future<void> runWork() {
final done = Completer<void>();
late final NativeCallable<ProgressNative> callback;
// listener() can be called from any thread. The call is queued
// and the Dart closure runs later on this isolate's event loop.
callback = NativeCallable<ProgressNative>.listener((int percent) {
print('progress: $percent%');
if (percent == 100) {
callback.close();
done.complete();
}
});
startWork(callback.nativeFunction);
print('start_work returned immediately');
return done.future;
}
Future<void> main() async {
await runWork();
print('done');
}
Output:
start_work returned immediately
progress: 25%
progress: 50%
progress: 75%
progress: 100%
done
An open listener keeps the isolate alive, so close it when the work is done or the program never exits. Because the call is asynchronous, pointer arguments must still be valid when Dart gets around to running the callback; if C frees the data right after the call, pass a copy. For native calls that block for a long time, you can also make the call from a separate isolate; see Isolates.
Managing native resources with NativeFinalizer
A C library that hands out handles usually has a function to release them. Wrapping the handle in a Dart class and calling the release function from dispose() gives deterministic cleanup. A NativeFinalizer adds a safety net: it calls a C function with the handle once the Dart object becomes unreachable:
import 'dart:ffi';
// typedef struct Counter Counter; -- contents unknown to Dart
final class CounterHandle extends Opaque {}
final lib = DynamicLibrary.open('native.dll');
final counterNew = lib.lookupFunction<
Pointer<CounterHandle> Function(Int64),
Pointer<CounterHandle> Function(int)>('counter_new');
final counterIncrement = lib.lookupFunction<
Void Function(Pointer<CounterHandle>),
void Function(Pointer<CounterHandle>)>('counter_increment', isLeaf: true);
final counterValue = lib.lookupFunction<
Int64 Function(Pointer<CounterHandle>),
int Function(Pointer<CounterHandle>)>('counter_value', isLeaf: true);
// The finalizer needs the raw C function pointer: void counter_free(Counter*)
final counterFreePtr =
lib.lookup<NativeFunction<Void Function(Pointer<Void>)>>('counter_free');
final counterFree = counterFreePtr.asFunction<void Function(Pointer<Void>)>();
final _finalizer = NativeFinalizer(counterFreePtr);
// Implementing Finalizable keeps `this` alive until native calls finish.
class Counter implements Finalizable {
final Pointer<CounterHandle> _ptr;
bool _disposed = false;
Counter(int start) : _ptr = counterNew(start) {
_finalizer.attach(this, _ptr.cast(), detach: this, externalSize: 8);
}
void increment() => counterIncrement(_check());
int get value => counterValue(_check());
// Deterministic cleanup; the finalizer is only a safety net.
void dispose() {
if (_disposed) return;
_disposed = true;
_finalizer.detach(this);
counterFree(_ptr.cast());
}
Pointer<CounterHandle> _check() {
if (_disposed) throw StateError('Counter used after dispose()');
return _ptr;
}
}
void main() {
final c = Counter(10);
c.increment();
c.increment();
print(c.value);
c.dispose();
try {
c.value;
} on StateError catch (e) {
print(e.message);
}
// Never disposed: counter_free runs when the object is garbage
// collected, or at the latest when the isolate shuts down.
final leaked = Counter(0)..increment();
print(leaked.value);
}
Output:
12
Counter used after dispose()
1
Details that matter:
NativeFinalizertakes a pointer to a C function with signaturevoid (*)(void*). The C function runs directly, without calling back into Dart, so it also runs on isolate shutdown.- The class implements
Finalizable. That tells the compiler to keep the object alive until the end of every method that uses it. Without it, the object could be collected (and the handle freed) whilecounterValue(_ptr)is still running. externalSizetells the garbage collector how much native memory the object holds, so it can schedule collections sensibly.isLeaf: truemarks functions that are short and never call back into Dart. Leaf calls skip some VM bookkeeping and are noticeably cheaper.
Finalizers are not guaranteed to run promptly. Use dispose() (or try/finally) for anything scarce, such as file handles or locks. See Memory and garbage collection for how Dart's GC decides when objects die.
@Native functions and build hooks
The examples above load libraries by path at runtime, which means you have to ship the library and find it. The modern alternative is an @Native external function plus a build hook that compiles the C code as part of dart run, dart test and dart build.
Add the hook packages:
dart pub add hooks code_assets native_toolchain_c
Project layout:
my_package/
hook/build.dart
src/native_add.c
lib/native_add.dart
bin/main.dart
hook/build.dart compiles src/native_add.c with the platform's C compiler (MSVC on Windows, clang or gcc elsewhere) and registers the result as a code asset for the package:my_package/native_add.dart library:
import 'package:hooks/hooks.dart';
import 'package:native_toolchain_c/native_toolchain_c.dart';
void main(List<String> args) async {
await build(args, (input, output) async {
final builder = CBuilder.library(
name: 'native_add',
assetName: 'native_add.dart',
sources: ['src/native_add.c'],
);
await builder.run(input: input, output: output);
});
}
src/native_add.c contains add and average, the same code as in native.c above. The Dart side declares the functions with @Native. There is no DynamicLibrary and no lookup: the symbol is resolved through the asset whose id matches the library's URI:
// lib/native_add.dart
import 'dart:ffi';
@Native<Int32 Function(Int32, Int32)>()
external int add(int a, int b);
@Native<Double Function(Pointer<Double>, Int32)>(isLeaf: true)
external double average(Pointer<Double> values, int count);
// bin/main.dart
import 'dart:ffi';
import 'dart:typed_data';
import 'package:my_package/native_add.dart';
void main() {
print(add(20, 22));
final data = Float64List.fromList([2, 4, 6, 8, 10]);
print(average(data.address, data.length));
}
Output of dart run bin/main.dart (the first run also shows compiler output from the hook):
42
6.0
@Native functions have another advantage: in a leaf call you can pass typedData.address directly, and C reads the Dart list's memory without first copying it into a malloc'd buffer. This only works as an argument to an @Native function marked isLeaf: true; with a function from lookupFunction it's a compile error.
dart build cli bundles the compiled library with the executable, so the result is self-contained. See Compiling to executables.
Generating bindings with ffigen
Writing signatures by hand is fine for a few functions, but for a real C library with hundreds of functions and structs use ffigen. It parses C headers with libclang and generates the Struct classes and function bindings, either as @Native externals or as a class wrapping a DynamicLibrary.
Summary
| Task | API |
|---|---|
| Load a library | DynamicLibrary.open, .process(), .executable() |
| Bind a function | lib.lookupFunction<NativeSig, DartSig>('name') or @Native |
| Allocate and free | malloc/calloc and .free, or using((arena) { ... }) |
| Read and write memory | p.value, p[i], p.ref, p.asTypedList(n) |
| Strings | toNativeUtf8(), toDartString(), Utf16 for wchar_t* |
| Structs | Struct, Union, @Array, @Packed, Opaque |
| Synchronous callbacks | Pointer.fromFunction, NativeCallable.isolateLocal |
| Callbacks from other threads | NativeCallable.listener |
| Automatic cleanup | NativeFinalizer with Finalizable |
Rules of thumb: free memory with the allocator that created it, let C free what C allocated, keep native signatures in sync with the C headers, and close every NativeCallable you open.