Flutter 如何调用dylib?

17 min read

Flutter 可以通过插件方式调用 dylib,具体步骤如下:

  1. 创建一个 Flutter 项目,并添加 dart:ffidart:io 依赖;

  2. 编写 C/C++ 代码,并将其编译成动态库;

  3. 在 Flutter 项目中,创建一个插件,并将动态库文件复制到插件的 iosandroid 文件夹中;

  4. 在插件中编写 Dart 代码,通过 DynamicLibrary 类加载动态库文件,并通过 ffi 库中提供的接口调用 C/C++ 函数。

以下是一个简单的示例,展示了如何在 Flutter 中调用一个 C 函数:

C/C++ 代码:

#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

编译为动态库:

gcc -dynamiclib -o libtest.dylib test.c

Flutter 插件中的 Dart 代码:

import 'dart:ffi';
import 'dart:io';

final DynamicLibrary testLib = Platform.isAndroid
  ? DynamicLibrary.open('libtest.so')
  : DynamicLibrary.process();

typedef AddFunc = Int32 Function(Int32 a, Int32 b);
final add = testLib.lookupFunction<AddFunc, AddFunc>('add');

void main() {
    print(add(1, 2));
}

在上面的代码中,我们先通过 Platform.isAndroid 判断当前运行环境是 Android 还是 iOS,然后通过 DynamicLibrary.openDynamicLibrary.process 构造 DynamicLibrary 对象,最后通过 lookupFunction 方法获取需要调用的 C 函数。调用 C 函数的方式与普通 Dart 函数一样,使用函数名和参数列表即可。