FFI async callback
2020-12-29 本文已影响0人
CentForever
C++ 层
DART_EXPORT void RegisterMyCallbackBlocking(Dart_Port send_port,
intptr_t (*callback1)(intptr_t)) {
my_callback_blocking_fp_ = callback1;
my_callback_blocking_send_port_ = send_port;
}
DART_EXPORT void RegisterMyCallbackNonBlocking(Dart_Port send_port,
void (*callback)(intptr_t)) {
my_callback_non_blocking_fp_ = callback;
my_callback_non_blocking_send_port_ = send_port;
}
intptr_t (*my_callback_blocking_fp_)(intptr_t);
Dart_Port my_callback_blocking_send_port_;
void (*my_callback_non_blocking_fp_)(intptr_t);
Dart_Port my_callback_non_blocking_send_port_;
Dart 层
int globalResult = 0;
int numCallbacks1 = 0;
int numCallbacks2 = 0;
final dl = dlopenPlatformSpecific("ffi_test_functions");
final registerCallback1 = dl.lookupFunction<
Void Function(Int64 sendPort,
Pointer<NativeFunction<IntPtr Function(IntPtr)>> functionPointer),
void Function(int sendPort,
Pointer<NativeFunction<IntPtr Function(IntPtr)>> functionPointer)>(
'RegisterMyCallbackBlocking');
final registerCallback2 = dl.lookupFunction<
Void Function(Int64 sendPort,
Pointer<NativeFunction<Void Function(IntPtr)>> functionPointer),
void Function(int sendPort,
Pointer<NativeFunction<Void Function(IntPtr)>> functionPointer)>(
'RegisterMyCallbackNonBlocking');
final callback1FP = Pointer.fromFunction<IntPtr Function(IntPtr)>(callback1, 0);
final callback2FP = Pointer.fromFunction<Void Function(IntPtr)>(callback2);
int callback1(int a) {
print("Dart: callback1($a).");
numCallbacks1++;
return a + 3;
}
void callback2(int a) {
print("Dart: callback2($a).");
globalResult += a;
numCallbacks2++;
}
调用
print("Dart: Setup.");
Expect.isTrue(NativeApi.majorVersion == 2);
Expect.isTrue(NativeApi.minorVersion >= 0);
final initializeApi = dl.lookupFunction<IntPtr Function(Pointer<Void>),
int Function(Pointer<Void>)>("InitDartApiDL");
Expect.isTrue(initializeApi(NativeApi.initializeApiDLData) == 0);
final interactiveCppRequests = ReceivePort()..listen(requestExecuteCallback);
final int nativePort = interactiveCppRequests.sendPort.nativePort;
registerCallback1(nativePort, callback1FP);
registerCallback2(nativePort, callback2FP);