dart:ffi
- Dart course
- Expert
- Lesson 13/47
- 5 min
Learn C interop with dart:ffi.
dart:ffi
dart:ffi is Dart's library for communicating with C libraries. FFI (Foreign Function Interface) lets Dart code call C functions. It is imported with import 'dart:ffi';.
FFI is useful for performance-critical operations or for reusing existing C libraries. Dart supports FFI on native platforms (Flutter native, CLI); not on the web. With dart:ffi, a DynamicLibrary is loaded and functions are bound with lookupFunction.
FFI limits
dart:ffi works only on native platforms; it is not supported on the web. To load a C library, use DynamicLibrary.open('libmylib.so') (Linux), .dylib (macOS), or .dll (Windows).
FFI provides Pointer, Struct, and Union types to share data between Dart and C. These types give direct memory access; use them carefully. Incorrect use can corrupt memory.
Practice An FfiBinding class
Add import 'dart:ffi'; to import the FFI library. Define an FfiBinding class with final String name; final String dartType; FfiBinding(this.name, this.dartType); field and constructor. Add a String describe() => '$name: $dartType'; method. In main create final b = FfiBinding('add', 'int Function(int, int)');; print with print(b.describe());.
Starter code
void main() {
// import dart:ffi
// define an FfiBinding class (name, dartType; describe method)
// create an FfiBinding; print describe()
}Sample solution
import 'dart:ffi';
class FfiBinding {
final String name;
final String dartType;
FfiBinding(this.name, this.dartType);
String describe() => '$name: $dartType';
}
void main() {
final b = FfiBinding('add', 'int Function(int, int)');
print(b.describe());
}Expected output
add: int Function(int, int)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does dart:ffi provide?
- Web rendering
- Communication with C libraries Correct answer
- Garbage collection
- UI widgets
Explanation: dart:ffi is Dart's C interop library.
2 dart:ffi import
import '____';
void main() {
print('ffi loaded');
}
import 'dart:ffi';
void main() {
print('ffi loaded');
}
Explanation: dart:ffi is the FFI library.
3 Match the FFI parts
| Term | Meaning |
|---|---|
dart:ffi |
C interop library |
DynamicLibrary |
C library loader |
lookupFunction |
Function binder |
Pointer |
Memory address |