示例工程 ch10-ffi
ch10-ffi/lib/bindings/c_generated_library.dart
/// 用 ffigen 生成的绑定调用同一个 C 库。
///
/// 与手写版(c_bindings.dart)对照:
/// - 生成版不需要写 typedef,符号名/参数类型全部来自 add.h;
/// - `CAdd(lib)` 直接拿到 `add_i32` 这样的方法;
/// - 头文件改名/加参数后重新跑 ffigen,绑定自动同步。
///
/// 代价是生成代码不可读(但也不该读),以及引入 ffigen + libclang 的构建依赖。
library;
import 'dart:ffi';
import 'package:ffi/ffi.dart';
import '../add_library.dart';
import '../loader.dart';
import 'c_bindings_generated.dart';
class CGeneratedLibrary implements AddLibrary {
CGeneratedLibrary._(this._add);
factory CGeneratedLibrary.open() {
// CAdd 需要一个 DynamicLibrary;loader 负责按平台找文件。
final CAdd add = CAdd(NativeLoader.open('add_c'));
return CGeneratedLibrary._(add);
}
final CAdd _add;
@override
String get language => 'C (ffigen)';
@override
int addI32(int a, int b) => _add.add_i32(a, b);
@override
double mulF64(double a, double b) => _add.mul_f64(a, b);
@override
String concat(String a, String b) {
// 生成版把 char* 映射成 Pointer<Char>,Utf8 只是"语义上的 Uint8",
// 两者都是 1 字节,cast 即可。
final Pointer<Char> pa = a.toNativeUtf8().cast<Char>();
final Pointer<Char> pb = b.toNativeUtf8().cast<Char>();
Pointer<Char> result = nullptr;
try {
result = _add.concat_strings(pa, pb);
if (result == nullptr) {
throw StateError('C concat_strings 返回了 NULL');
}
return result.cast<Utf8>().toDartString();
} finally {
calloc.free(pa);
calloc.free(pb);
if (result != nullptr) _add.free_string(result);
}
}
@override
int applyCallback(int Function(int x) fn, int x) {
final NativeCallable<Int32 Function(Int32)> cb =
NativeCallable<Int32 Function(Int32)>.isolateLocal(
(int v) => fn(v),
exceptionalReturn: -1,
);
try {
return _add.apply_cb(cb.nativeFunction, x);
} finally {
cb.close();
}
}
}