3

I try to call a dart method from my C++ library. When i call it direkt in the same method where I set the pointer it works. When I call it later, in this case from another C++ mehtod, I get a error.

Is there some way to invoke the main dart thread in C ++? Or do you have another solution for it?

Dart Part:

@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++ Part

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);
  }
}

Here the log prints "Hey Dart, i am done! Result: 500".

Later the c++ Part calls

nativeHandler(nullptr,1000); 

in another method and i get the error:

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
Chris
  • 71
  • 4
  • In your demo, can C++ successfully call the dart method? I didn't know how C++ calls dart's methods before. [Here is my question](https://stackoverflow.com/questions/61676507/c-call-dart-function-in-flutter) – Liu Silong Apr 27 '21 at 08:18
  • Is this solved? Please add the answer if you did – Sanjay Jan 09 '22 at 09:13

1 Answers1

0

C++ side call's thread maybe not in isolate thread, so Flutter engine throw error. Your can try Dart_Port_DL replace c++ call dart code.

// The function is thread-safe; you can call it anywhere on your C++ code
 Dart_PostCObject_DL(m_dart_port_dl, &msg);
act262
  • 463
  • 4
  • 7