/// Rust 动态库(cargo 产出的 cdylib)的绑定。 /// /// 符号名与 C 版完全一致(`add_i32` 等),因为 Rust 侧用了 `#[no_mangle] + extern "C"`。 /// 这正是 FFI 的价值:**调用方只关心 C ABI,不关心实现语言**。 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 Function(Pointer a, Pointer b); typedef ConcatDart = Pointer Function(Pointer a, Pointer b); typedef FreeStringNative = Void Function(Pointer s); typedef FreeStringDart = void Function(Pointer s); typedef ApplyCbNative = Int32 Function( Pointer> cb, Int32 x); typedef ApplyCbDart = int Function( Pointer> cb, int x); class RustLibrary implements AddLibrary { RustLibrary._(DynamicLibrary lib) : _addI32 = lib.lookupFunction('add_i32'), _mulF64 = lib.lookupFunction('mul_f64'), _concat = lib.lookupFunction('concat_strings'), _freeString = lib.lookupFunction('free_string'), _applyCb = lib.lookupFunction('apply_cb'); factory RustLibrary.open() => RustLibrary._(NativeLoader.open('add_rust')); final AddI32Dart _addI32; final MulF64Dart _mulF64; final ConcatDart _concat; final FreeStringDart _freeString; final ApplyCbDart _applyCb; @override String get language => 'Rust'; @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) { final Pointer pa = a.toNativeUtf8(); final Pointer pb = b.toNativeUtf8(); Pointer result = nullptr; try { result = _concat(pa, pb); if (result == nullptr) { throw StateError('Rust concat_strings 返回了 NULL'); } return result.toDartString(); } finally { calloc.free(pa); calloc.free(pb); // Rust 侧是 CString::into_raw,必须还给 Rust 的 free_string(内部 drop 释放) if (result != nullptr) _freeString(result); } } @override int applyCallback(int Function(int x) fn, int x) { // 同步回调用 isolateLocal(listener 只能返回 void) final NativeCallable cb = NativeCallable.isolateLocal( (int v) => fn(v), exceptionalReturn: -1, // 回调里抛异常时返回给原生侧的值 ); try { return _applyCb(cb.nativeFunction, x); } finally { cb.close(); } } }