1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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');
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) {
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');
}
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) {
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();
}
}
}