Challenge 2
- Flutter course
- Expert
- Lesson 37/39
- 3 min
Call math from a C library via dart:ffi.
C calls with dart:ffi
dart:ffi lets you call C libraries directly from Dart. You open process symbols with DynamicLibrary.process() and wrap a C function into a Dart function with lookupFunction. Two typedefs are needed: the native signature and the Dart signature.
typedef SqrtNative = Double Function(Double);
typedef SqrtDart = double Function(double);
final lib = DynamicLibrary.process();
final sqrt = lib.lookupFunction<SqrtNative, SqrtDart>('sqrt');
print(sqrt(9)); // 3.0Practice sqrt call
Define SqrtNative and SqrtDart typedefs. Open the library with DynamicLibrary.process(). Get the sqrt function via lookupFunction. In main call the square root function with 9 and print the result.
Starter code
import 'dart:ffi';
// İki typedef tanımla: yerel ve Dart imzası
// Kütüphaneyi aç
// karekök fonksiyonunu sarmala
// main: fonksiyonu 9 ile çağır ve yazdır
void main() {
}Sample solution
import 'dart:ffi';
typedef SqrtNative = Double Function(Double);
typedef SqrtDart = double Function(double);
void main() {
final lib = DynamicLibrary.process();
final sqrt = lib.lookupFunction<SqrtNative, SqrtDart>('sqrt');
print(sqrt(9));
}Expected output
3.0
Practice Compute hypotenuse
Use the same typedefs and sqrt wrapper. Write a hypotenuse(double a, double b) function that returns sqrt(a * a + b * b). In main print the result of hypotenuse(3, 4).
Starter code
import 'dart:ffi';
// İki typedef: yerel ve Dart imzası
// Kütüphaneyi aç ve karekök fonksiyonunu sarmala
// hypotenuse(a, b) fonksiyonu yaz
// main: hipotenüs(3, 4) sonucunu yazdır
void main() {
}Sample solution
import 'dart:ffi';
typedef SqrtNative = Double Function(Double);
typedef SqrtDart = double Function(double);
double hypotenuse(double a, double b) {
final lib = DynamicLibrary.process();
final sqrt = lib.lookupFunction<SqrtNative, SqrtDart>('sqrt');
return sqrt(a * a + b * b);
}
void main() {
print(hypotenuse(3, 4));
}Expected output
5.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does lookupFunction do?
- Opens a platform channel
- Compiles the C library
- Performs memory management
- Wraps a C function as a Dart function Correct answer
Explanation: lookupFunction looks up a C symbol and wraps it into a safe Dart call; it handles the conversion between two typedefs.
2 Open DynamicLibrary
final lib = ____;
final sqrt = lib.lookupFunction<SqrtNative, SqrtDart>('sqrt');
final lib = DynamicLibrary.process();
final sqrt = lib.lookupFunction<SqrtNative, SqrtDart>('sqrt');
Explanation: DynamicLibrary.process() opens all symbols in the process; it provides access to standard C functions like sqrt.
3 FFI parts
| Term | Meaning |
|---|---|
DynamicLibrary |
Loads the C library |
lookupFunction |
Wraps the C function |
Double |
FFI double type |
typedef |
Function signature alias |