我尝试从我的 C++ 库调用 Dart 方法。当我在设置指针的同一方法中直接调用它时,它就可以工作。当我稍后调用它时,在本例中是从另一个 C++ 方法调用它时,我收到错误。
有没有办法在C++中调用Dart主线程?或者您有其他解决方案吗?
飞镖部分:
@override
void initState() {
initHandler(Pointer.fromFunction<result_callback>(resultCallback));
super.initState();
}
static void resultCallback(Pointer<Void> ptr, int result) {
print("Hey Dart, i am done! Result: " + result.toString());
}
typedef result_callback = Void Function(Pointer<Void>, ffi.Int32);
typedef _init = Void Function(Pointer<NativeFunction<result_callback>>);
typedef _InitFunc = void Function(Pointer<NativeFunction<result_callback>>);
final _InitFunc initHandler = cppLib.lookup<NativeFunction<_init>>('initHandler').asFunction();
C++部分:
typedef void(*dartResultHandler)(void*, int32_t);
dartResultHandler nativeHandler;
void setDartHandler(dartResultHandler _dartResultHandler) {
nativeHandler = _dartResultHandler;
}
extern "C" {
__attribute__((visibility("default"))) __attribute__((used)) void initHandler(void (*_dartResultHandler)(void*, int32_t)) {
_dartResultHandler(nullptr, 500);
setDartHandler(_dartResultHandler);
}
}
这里打印日志:
嘿达特,我完成了!结果:500
后来,C++部分在另一个方法中调用
nativeHandler(nullptr,1000);
,我得到这个错误:
E/Dart (26335): ../../third_party/dart/runtime/vm/runtime_entry.cc: 3518: error: Cannot invoke native callback outside an isolate.
E/DartVM (26335): version=2.10.4 (stable) (Wed Nov 11 13:35:58 2020 +0100) on "android_arm64"
E/DartVM (26335): pid=26335, thread=32701, isolate_group=(nil)(0x0), isolate=(nil)(0x0)
E/DartVM (26335): isolate_instructions=0, vm_instructions=79df5f1720
E/DartVM (26335): pc 0x00000079df70460c fp 0x00000079c177b780 /data/app/com.example.libtest_flutter-sP2r6HRVpXyy23c0p-vDFQ==/lib/arm64/libflutter.so+0x172860c
E/DartVM (26335): -- End of DumpStackTrace
C++ 侧调用的线程可能不在隔离线程中,因此 Flutter 引擎会抛出错误。 您可以尝试
Dart_Port_DL
替换 C++ 调用 dart 代码。
// The function is thread-safe; you can call it anywhere on your C++ code
Dart_PostCObject_DL(m_dart_port_dl, &msg);