lookupFunction
- Flutter course
- Expert
- Lesson 23/39
- 4 min
Bind a C function to Dart with lookupFunction.
lookupFunction
lookupFunction makes a C function in a DynamicLibrary callable from Dart. It takes two type parameters: a NativeFunction (C side) and a Dart function type. The returned value is a Dart function.
final topla = lib.lookupFunction<NativeTopla, DartTopla>('topla');NativeFunction and pointer
NativeFunction carries the C function signature (with types like Int32, Pointer). lookupFunction converts this signature to the Dart side, so pointers and memory addresses are shared safely.
Practice Look up the getpid symbol
First define the typedefs NativeGetpid = Int32 Function() and DartGetpid = int Function(). In main, get a library with DynamicLibrary.process(), look up the 'getpid' symbol with lookupFunction, and print 'lookup hazir'.
Starter code
import 'dart:ffi';
// NativeGetpid ve DartGetpid typedef'lerini tanımla (Int32/int Function())
void main() {
// Süreç kütüphanesini al
// lookupFunction ile getpid sembolünü ara
// 'lookup hazir' yazdır
}Sample solution
import 'dart:ffi';
typedef NativeGetpid = Int32 Function();
typedef DartGetpid = int Function();
void main() {
final lib = DynamicLibrary.process();
final getpid = lib.lookupFunction<NativeGetpid, DartGetpid>('getpid');
print('lookup hazir');
}Expected output
lookup hazir
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does lookupFunction return?
- A widget
- A Dart function Correct answer
- A string
- A C pointer
Explanation: lookupFunction converts a C symbol into a Dart function; the returned value can be called directly like a Dart function.
2 lookupFunction call
final topla = lib.____<NativeTopla, DartTopla>('topla');
final topla = lib.lookupFunction<NativeTopla, DartTopla>('topla');
Explanation: lookupFunction converts a C symbol to a Dart function with two type parameters; lookup returns only a NativeFunction, getFunction and findSymbol do not exist in dart:ffi.
3 lookupFunction matches
| Term | Meaning |
|---|---|
lookupFunction |
Binds a C function |
NativeFunction |
C function type |
pointer |
Memory address |
symbol |
C function name |