Native function
- Dart course
- Expert
- Lesson 15/47
- 5 min
Learn native functions with lookupFunction.
Native function
Native function binding connects a C-side function so it can be called from Dart. Two typedefs are needed: the native signature (typedef NativeAdd = Int32 Function(Int32, Int32);) and the Dart signature (typedef DartAdd = int Function(int, int);).
Binding is done with lib.lookupFunction<NativeAdd, DartAdd>('add'). lookupFunction wraps the native call into a Dart call. Return and parameter types are declared statically via typedefs; this preserves type safety.
Type mapping
FFI provides static mapping between native and Dart types. Int8, Int16, Int32, Int64 ↔ int; Float and Double ↔ double; Bool ↔ bool; Pointer<NativeType> ↔ Pointer<T>.
Mapping is checked at compile time; wrong mappings give a compile error. For example, a native function returning Int32 Function() cannot be bound with a String Function() Dart signature. Type safety is one of FFI's key advantages.
Practice A NativeBinding class
Define a NativeBinding class with final String symbol; final String dartType; NativeBinding(this.symbol, this.dartType); field and constructor. Add a String describe() => '$symbol → $dartType'; method. In main create final nb = NativeBinding('add', 'int Function(int, int)');; print with print(nb.describe());.
Starter code
void main() {
// define a NativeBinding class (symbol, dartType; describe)
// create a NativeBinding; print describe()
}Sample solution
class NativeBinding {
final String symbol;
final String dartType;
NativeBinding(this.symbol, this.dartType);
String describe() => '$symbol → $dartType';
}
void main() {
final nb = NativeBinding('add', 'int Function(int, int)');
print(nb.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 Match the native function parts
| Term | Meaning |
|---|---|
NativeAdd |
Native signature |
DartAdd |
Dart signature |
lookupFunction |
Binder |
Int32 |
Native type |
2 What does lookupFunction do?
- Loads a library
- Reads a file
- Does UI rendering
- Binds a native function to Dart Correct answer
Explanation: lookupFunction binds a native function to the Dart side.
3 A lookupFunction call
final add = lib.lookupFunction<NativeAdd, ____>('add');
final add = lib.lookupFunction<NativeAdd, DartAdd>('add');
Explanation: lookupFunction<NativeAdd, DartAdd> specifies both signatures.