Flutter 使用 ffigen 生成 FFI 的绑定

ffigen 的作用


当你使用的C代码库内有大量API时,要花费大量时间编写 C 函数的 FFI 类型定义 及 对应的调用 C 函数 Dart Function,如下面两段代码。此时你可以使用 package:ffigen 绑定生成器,自动地从 C 头文件生成 FFI 包装,从而减少时间消耗。

为 C 函数的 FFI 类型签名的定义一个类型。

typedef hello_world_func = ffi.Void Function();

为调用 C 函数的变量定义一个类型。

typedef HelloWorld = void Function();

安装 LLVM


package:ffigen 依赖 LLVM,首先安装LLVM (9+)

ubuntu/linux

  1. Install libclangdev - sudo apt-get install libclang-dev.

Windows

  1. Install Visual Studio with C++ development support.
  2. Install LLVM or winget install -e –id LLVM.LLVM.

MacOS

  1. Install Xcode.
  2. Install LLVM - brew install llvm.
  3. 设置到环境变量,使用如下命令,或者自行添加到 .bash_profile
If you need to have llvm first in your PATH, run:
echo 'export PATH="/opt/homebrew/opt/llvm/bin:$PATH"' >> ~/.zshrc

For compilers to find llvm you may need to set:
export LDFLAGS="-L/opt/homebrew/opt/llvm/lib"
export CPPFLAGS="-I/opt/homebrew/opt/llvm/include"

配置


两种配置方式:

  1. In the project’s pubspec.yaml file under the key ffigen, running - dart run ffigen
ffigen:
output: 'hello_bindings_generated.dart'
headers:
entry-points:
- 'hello.h'
  1. Via a custom YAML file, then specify this file while running - dart run ffigen --config config.yaml
# Run with `flutter pub run ffigen --config ffigen.yaml`.
name: HelloBindings
description: |
Bindings for `src/hello.h`.

Regenerate bindings with `flutter pub run ffigen --config ffigen.yaml`.
output: 'lib/hello_bindings_generated.dart'
headers:
entry-points:
- 'src/hello.h'
include-directives:
- 'src/hello.h'
preamble: |
// ignore_for_file: always_specify_types
// ignore_for_file: camel_case_types
// ignore_for_file: non_constant_identifier_names
comments:
style: any
length: full

参考

  • https://pub.flutter-io.cn/packages/ffigen