win32 icon indicating copy to clipboard operation
win32 copied to clipboard

`midiInOpen` takes a Pointer to a callback but `Cannot invoke native callback outside an isolate`

Open akvus opened this issue 3 years ago • 1 comments

I'm trying to connect my MIDI device to a Flutter app running on Windows. I have the following:

final Pointer<HMIDIIN> hMidiDevice = malloc();

Pointer<NativeFunction<MidiInProc>> callbackPointer =
	Pointer.fromFunction(midiInCallback);

final result = midiInOpen(
  hMidiDevice,
  0,
  callbackPointer.address,
  0,
  CALLBACK_FUNCTION,
);
midiInStart(hMidiDevice.value);

midiInOpen takes a pointer to a function as 3rd argument. Here is my callback method:

static void midiInCallback(
	int hMidiIn,
	int wMsg,
	int dwInstance,
	int dwParam1,
	int dwParam2,
) {
	print('Message: $wMsg dwParam1: $dwParam1');
}

This compiles and works with a connected USB MIDI device. However, when I press a key on my MIDI device, then I get the following error:

../../third_party/dart/runtime/vm/runtime_entry.cc: 3657: error: Cannot invoke native callback outside an isolate.
pid=11004, thread=21860, isolate_group=(nil)(0000000000000000), isolate=(nil)(0000000000000000)
isolate_instructions=0, vm_instructions=7ffef50837c0
  pc 0x00007ffef51a3732 fp 0x00000057468ff990 angle::PlatformMethods::operator=+0x322d8a
-- End of DumpStackTrace

What am I doing wrong?

akvus avatar Aug 18 '22 17:08 akvus

The callback is invoked on a different thread, which is currently not (yet) supported in dart:ffi: https://github.com/dart-lang/sdk/issues/37022.

The work around is to use the dart_api with its native ports, see the linked issue.

dcharkes avatar Aug 19 '22 06:08 dcharkes

Closing this as Dart 3.1 introduced NativeCallable.listener, which can be used to create callbacks that allow native code to call into Dart code from any thread.

halildurmus avatar Sep 23 '23 18:09 halildurmus