๐ŸŽ“ A1Learner
๐Ÿ”
0 of 24 lessons completed

Dart FFI Calls

FFI lets Dart call native code directly. Dart opens a native library, looks up a function in it, and calls that function like a Dart function.

Looking up the abs function

The program opens the library and looks up abs with its two typedefs. Calling the function on -42 prints 42.

import 'dart:ffi';

typedef AbsNative = Int32 Function(Int32);
typedef AbsDart = int Function(int);

void main() {
  var lib = DynamicLibrary.open('libc.so.6');
  var abs = lib.lookupFunction<AbsNative, AbsDart>('abs');
  print(abs(-42));
}

Abs over several values

The same looked-up function runs three times. A positive number and zero pass through unchanged, and -9 becomes 9.

import 'dart:ffi';

typedef AbsNative = Int32 Function(Int32);
typedef AbsDart = int Function(int);

void main() {
  var lib = DynamicLibrary.open('libc.so.6');
  var abs = lib.lookupFunction<AbsNative, AbsDart>('abs');
  print(abs(7));
  print(abs(0));
  print(abs(-9));
}

Absolute differences of pairs

Each pair is a record of two numbers. The program subtracts the pair and passes the difference to abs, so every result is positive or zero.

import 'dart:ffi';

typedef AbsNative = Int32 Function(Int32);
typedef AbsDart = int Function(int);

void main() {
  var lib = DynamicLibrary.open('libc.so.6');
  var abs = lib.lookupFunction<AbsNative, AbsDart>('abs');
  var pairs = [(10, 4), (3, 8), (6, 6)];
  for (var (a, b) in pairs) {
    print(abs(a - b));
  }
}

Example

import 'dart:ffi';

typedef AbsNative = Int32 Function(Int32);
typedef AbsDart = int Function(int);

void main() {
  var lib = DynamicLibrary.open('libc.so.6');
  var abs = lib.lookupFunction<AbsNative, AbsDart>('abs');
  var readings = [-12, 5, -3, 0, 8];
  for (var reading in readings) {
    print(abs(reading));
  }
}

Key points

  • FFI calls native code directly from Dart.
  • DynamicLibrary.open opens the library, and lookupFunction finds one function in it by name.
  • Two typedefs describe the function, one in native types and one in Dart types.
  • The library name is platform-specific.
  • The name libc.so.6 is the Linux name, and the shipped code in this lesson is the Linux shape.
  • Only integer functions are shown in this lesson.
  • String and pointer functions need allocation helpers from a package, which this course does not use.

In this example, the looked-up abs function normalises each reading in the list. The negative readings -12 and -3 print as 12 and 3, and the other readings print unchanged.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

Why does this lesson show only integer functions through FFI?