示例工程 ch10-ffi
ch10-ffi/lib/bindings/go_bindings.dart
/// Go 动态库(`go build -buildmode=c-shared` 产出)的绑定。
///
/// 两个与 C/Rust 不同之处:
/// 1. 符号名必须**大写开头**(Go 的导出规则),即 `AddI32` 而不是 `add_i32`;
/// 2. 回调参数是 `uintptr`(Go 侧要借一层 C 函数才能调用函数指针),
/// 所以 Dart 侧传 `cb.nativeFunction.address`,而不是函数指针本身。
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(UintPtr cb, Int32 x);
typedef ApplyCbDart = int Function(int cb, int x);
class GoLibrary implements AddLibrary {
GoLibrary._(DynamicLibrary lib)
: _addI32 = lib.lookupFunction<AddI32Native, AddI32Dart>('AddI32'),
_mulF64 = lib.lookupFunction<MulF64Native, MulF64Dart>('MulF64'),
_concat = lib.lookupFunction<ConcatNative, ConcatDart>('ConcatStrings'),
_freeString = lib.lookupFunction<FreeStringNative, FreeStringDart>('FreeString'),
_applyCb = lib.lookupFunction<ApplyCbNative, ApplyCbDart>('ApplyCb');
factory GoLibrary.open() => GoLibrary._(NativeLoader.open('add_go'));
final AddI32Dart _addI32;
final MulF64Dart _mulF64;
final ConcatDart _concat;
final FreeStringDart _freeString;
final ApplyCbDart _applyCb;
@override
String get language => 'Go';
@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<Utf8> pa = a.toNativeUtf8();
final Pointer<Utf8> pb = b.toNativeUtf8();
Pointer<Utf8> result = nullptr;
try {
result = _concat(pa, pb);
if (result == nullptr) {
throw StateError('Go ConcatStrings 返回了 NULL');
}
return result.toDartString();
} finally {
calloc.free(pa);
calloc.free(pb);
// Go 侧用 C.CString(malloc)分配,由 FreeString(C.free)归还。
if (result != nullptr) _freeString(result);
}
}
@override
int applyCallback(int Function(int x) fn, int x) {
// 同步回调用 isolateLocal(listener 只能返回 void)
final NativeCallable<Int32 Function(Int32)> cb =
NativeCallable<Int32 Function(Int32)>.isolateLocal(
(int v) => fn(v),
exceptionalReturn: -1, // 回调里抛异常时返回给原生侧的值
);
try {
return _applyCb(cb.nativeFunction.address, x);
} finally {
cb.close();
}
}
}