CodeBlanks Logo Icon CodeBlanks

Summary - FFI

Combine DynamicLibrary, lookupFunction and Pointer to write a native wrapper.

Summary: FFI

In this group we covered the core pieces of dart:ffi: dart:ffi is the C interop library, DynamicLibrary loads C libraries, lookupFunction binds native functions.

Struct represents C structs, Pointer manages memory addresses. dart:ffi works on native platforms, not on the web. In this summary you will write a native wrapper that combines all of these pieces.

Practice Summary: A NativeWrapper class

Define a NativeWrapper class with final String library; final String symbol; NativeWrapper(this.library, this.symbol); field and constructor. Add a String describe() => '$library :: $symbol'; method. In main create final w = NativeWrapper('libmylib.so', 'add');; print with print(w.describe());.

Starter code

main.dart
void main() {
  // define a NativeWrapper class (library, symbol; describe)
  // create a NativeWrapper; print describe()
}

Sample solution

main.dart
class NativeWrapper {
  final String library;
  final String symbol;
  NativeWrapper(this.library, this.symbol);
  String describe() => '$library :: $symbol';
}

void main() {
  final w = NativeWrapper('libmylib.so', 'add');
  print(w.describe());
}

Expected output

libmylib.so :: add

Questions and answers

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

1 What is DynamicLibrary used for?

  • For UI rendering
  • For garbage collection
  • For loading C libraries Correct answer
  • For package download

Explanation: DynamicLibrary loads C libraries.

2 Match the FFI parts

Term Meaning
dart:ffi C interop
DynamicLibrary Library loader
lookupFunction Symbol lookup
Pointer Memory address

3 A native function symbol

Question
final symbol = '____';
print(symbol);
Answer
final symbol = 'add';
print(symbol);

Explanation: 'add' is a common C function symbol.

All lessons in Expert