flutter ffi如何使用
我想在Flutter项目中使用FFI调用本地代码,但不太清楚具体该如何操作。能否详细说明一下Flutter FFI的使用步骤?包括如何配置Dart代码与本地代码的交互、数据类型的映射关系、以及如何处理内存管理等问题?最好能提供一个简单的示例代码说明基本的调用流程。
2 回复
Flutter FFI 用于调用 C/C++ 代码。步骤:
- 在
pubspec.yaml添加ffi依赖。 - 编写 C 代码并编译为动态库(如
.so、.dll)。 - 使用
DynamicLibrary.open加载库。 - 用
ffi定义函数签名并调用。
示例:调用 C 的sum函数。
更多关于flutter ffi如何使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
Flutter FFI(Foreign Function Interface)允许在Dart代码中调用C语言编写的原生库,实现高性能计算或复用现有C代码。以下是基本使用步骤:
-
添加依赖
在pubspec.yaml中添加:dependencies: ffi: ^2.0.1 -
创建C代码
编写一个简单的C函数,保存为native_add.c:int add(int a, int b) { return a + b; } -
编译为动态库
- Windows: 使用MinGW编译为
.dll - macOS/Linux: 用GCC编译为
.dylib或.so
示例命令(Linux):
gcc -shared -o libnative_add.so native_add.c - Windows: 使用MinGW编译为
-
在Flutter中加载库
import 'dart:ffi'; import 'package:ffi/ffi.dart'; // 加载动态库 final dylib = DynamicLibrary.open('libnative_add.so'); // 定义函数签名 typedef NativeAdd = Int32 Function(Int32, Int32); typedef Add = int Function(int, int); // 获取函数 final Add add = dylib .lookup<NativeFunction<NativeAdd>>('add') .asFunction<Add>(); -
调用函数
void main() { print(add(3, 5)); // 输出:8 }
关键注意事项:
- 动态库需放置在项目内(如
android/app/src/main/jniLibs),并配置构建路径 - 数据类型需严格匹配(如
Int32对应int) - 内存管理需谨慎,避免泄漏(使用
allocate/free)
适用于性能敏感操作、硬件交互或复用C/C++库的场景。

