flutter开发中使用 dart:ffi 与 C 进行交互[动态库]

278 阅读1分钟

使用 dart:ffi 与 C 进行交互

FFI 指的是 [外部函数接口] / [foreign function interface. ])

构建 C 代码库时将创建几个文件,包括动态库 libhello.dylib(仅 macOS)、 libhello.dll(仅 Windows)或 libhello.so(仅 Linux)。

Linux系统相关编译so库

Linux系统相关

1. 通过mobaxterm启动Linux终端

2. 更新源 sudo apt update

3. 安装部分依赖(下⾯有很多重复的库,没关系)

a. sudo apt-get install clang cmake git ninja-build pkg-config

libgtk-3-dev liblzma-dev libstdc++-12-dev

b. sudo apt install clang cmake build-essential pkg-config libegl1-

mesa-dev libxkbcommon-dev libgles2-mesa-dev

c. sudo apt install curl unzip git clang cmake pkg-config

构建并运行

以下是构建动态库并执行 Dart 应用的示例:

$ cd hello_library
$ cmake .
...
$ make
...
/// 到这里so库就编译完成

    // flutter项目中使用
$ cd ..
$ dart pub get
$ dart run hello.dart
Hello World
// hello.dart 
import 'dart:ffi' as ffi;  
import 'dart:io' show Platform, Directory;  
  
import 'package:path/path.dart' as path;  
  
// FFI signature of the hello_world C function  
typedef HelloWorldFunc = ffi.Void Function();  
// Dart type definition for calling the C foreign function  
typedef HelloWorld = void Function();  
  
void main() {  
    // Open the dynamic library  
    var libraryPath =  
    path.join(Directory.current.path, 'hello_library', 'libhello.so');  

    if (Platform.isMacOS) {  
        libraryPath =  
        path.join(Directory.current.path, 'hello_library', 'libhello.dylib');  
    }  

    if (Platform.isWindows) {  
        libraryPath = path.join(  
        Directory.current.path, 'hello_library', 'Debug', 'hello.dll');  
    }  

    final dylib = ffi.DynamicLibrary.open(libraryPath);  

    // Look up the C function 'hello_world'  
    final HelloWorld hello = dylib  
    .lookup<ffi.NativeFunction<HelloWorldFunc>>('hello_world')  
    .asFunction();  
    // Call the function  
    hello();  
}