CodeBlanks Logo Icon CodeBlanks

Summary - dart:ffi

Combine DynamicLibrary and lookupFunction to call C.

Summary - dart:ffi

Calling a C function combines two steps: load the library with DynamicLibrary.open, and bind the function to Dart with lookupFunction. Define the signatures with two typedefs (Native and Dart).

final lib = DynamicLibrary.open('libmath.so');
final topla = lib.lookupFunction<NativeTopla, DartTopla>('topla');
print(topla(2, 3));

Practice Call the abs function

First define the typedefs NativeAbs = Int32 Function(Int32) and DartAbs = int Function(int). In main, get lib with DynamicLibrary.process(), look up the 'abs' symbol with lookupFunction, and print the result of abs(-5).

Starter code

main.dart
import 'dart:ffi';

// NativeAbs ve DartAbs typedef'lerini tanımla (Int32/int Function(Int32/int))

void main() {
  // Süreç kütüphanesini al
  // lookupFunction ile abs sembolünü ara
  // negatif bir sayıyı mutlak değere çevirip yazdır
}

Sample solution

main.dart
import 'dart:ffi';

typedef NativeAbs = Int32 Function(Int32);
typedef DartAbs = int Function(int);

void main() {
  final lib = DynamicLibrary.process();
  final abs = lib.lookupFunction<NativeAbs, DartAbs>('abs');
  print(abs(-5));
}

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which two ffi tools combine to call a C function?

  • setState and build
  • DynamicLibrary and lookupFunction Correct answer
  • Widget and BuildContext
  • Navigator and Route

Explanation: DynamicLibrary loads the C library, lookupFunction converts the symbol to a Dart function; together they let you call the C function.

2 Call the topla function

Question
print(____(2, 3));
Answer
print(topla(2, 3));

Explanation: The Dart function returned by lookupFunction is called by its variable name; lib is the library, and call and run are not valid call syntax.

3 dart:ffi summary matches

Term Meaning
dart:ffi FFI framework
DynamicLibrary Library object
lookupFunction Symbol binding
typedef Signature definition

All lessons in Expert