示例工程 ch10-ffi

ch10-ffi/lib/bindings/c_bindings.dart

dart · 3.5 KB

/// C 动态库(libadd_c.so / .dylib / .dll)的绑定。
///
/// 这里用**手写绑定**,为的是把 ABI 细节讲清楚:
///   - lookupFunction 把符号地址变成 Dart 函数(原生签名 → Dart 签名);
///   - 每个参数/返回值都要有明确的 C 类型(`Int32` / `Double` / `Pointer<Utf8>`);
///   - 回调要声明成 `Pointer<NativeFunction<...>>`。
///
/// 工程里符号多了以后应该用 `ffigen` 从 `add.h` 生成(见 `ffigen.yaml`),
/// 手写版适合理解原理。
library;
 
import 'dart:ffi';
 
import 'package:ffi/ffi.dart';
 
import '../add_library.dart';
import '../loader.dart';
 
typedef AddI32Native = Int32 Function(Int32 a, Int32 b);
typedef AddI32Dart = int Function(int a, int b);
 
typedef MulF64Native = Double Function(Double a, Double b);
typedef MulF64Dart = double Function(double a, double b);
 
typedef ConcatNative = Pointer<Utf8> Function(Pointer<Utf8> a, Pointer<Utf8> b);
typedef ConcatDart = Pointer<Utf8> Function(Pointer<Utf8> a, Pointer<Utf8> b);
 
typedef FreeStringNative = Void Function(Pointer<Utf8> s);
typedef FreeStringDart = void Function(Pointer<Utf8> s);
 
typedef ApplyCbNative = Int32 Function(
    Pointer<NativeFunction<Int32 Function(Int32)>> cb, Int32 x);
typedef ApplyCbDart = int Function(
    Pointer<NativeFunction<Int32 Function(Int32)>> cb, int x);
 
class CLibrary implements AddLibrary {
  CLibrary._(DynamicLibrary lib)
      : _addI32 = lib.lookupFunction<AddI32Native, AddI32Dart>('add_i32'),
        _mulF64 = lib.lookupFunction<MulF64Native, MulF64Dart>('mul_f64'),
        _concat = lib.lookupFunction<ConcatNative, ConcatDart>('concat_strings'),
        _freeString = lib.lookupFunction<FreeStringNative, FreeStringDart>('free_string'),
        _applyCb = lib.lookupFunction<ApplyCbNative, ApplyCbDart>('apply_cb');
 
  /// 打开 `libadd_c` 并解析全部符号。
  factory CLibrary.open() => CLibrary._(NativeLoader.open('add_c'));
 
  final AddI32Dart _addI32;
  final MulF64Dart _mulF64;
  final ConcatDart _concat;
  final FreeStringDart _freeString;
  final ApplyCbDart _applyCb;
 
  @override
  String get language => 'C';
 
  @override
  int addI32(int a, int b) => _addI32(a, b);
 
  @override
  double mulF64(double a, double b) => _mulF64(a, b);
 
  @override
  String concat(String a, String b) {
    // toNativeUtf8() 用的是 calloc,必须由调用方 free —— 谁分配谁释放。
    final Pointer<Utf8> pa = a.toNativeUtf8();
    final Pointer<Utf8> pb = b.toNativeUtf8();
    Pointer<Utf8> result = nullptr;
    try {
      result = _concat(pa, pb);
      if (result == nullptr) {
        throw StateError('C concat_strings 返回了 NULL');
      }
      // toDartString() 会复制一份 Dart 字符串,之后才能安全释放原生内存。
      return result.toDartString();
    } finally {
      calloc.free(pa);
      calloc.free(pb);
      if (result != nullptr) _freeString(result);
    }
  }
 
  @override
  int applyCallback(int Function(int x) fn, int x) {
    // 同步回调必须用 isolateLocal:原生代码在当前线程直接调用它,要求
    // 「有返回值 + 同步执行」。listener 版本只能返回 void(它把调用排进事件队列)。
    // close() 之前必须保证原生侧不再持有它,否则就是 use-after-free。
    final NativeCallable<Int32 Function(Int32)> cb =
        NativeCallable<Int32 Function(Int32)>.isolateLocal(
      (int v) => fn(v),
      exceptionalReturn: -1, // 回调里抛异常时返回给原生侧的值
    );
    try {
      return _applyCb(cb.nativeFunction, x);
    } finally {
      cb.close();
    }
  }
}