如何使用 dart ffi 将回调传递给 win32 函数?

use*_*401 2 windows ffi dart flutter dart-ffi

我正在尝试将我的 MIDI 设备连接到 Windows 上运行的 Flutter 应用程序。我正在使用 win32 和 dart ffi。我有以下内容:

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);
Run Code Online (Sandbox Code Playgroud)

midiInOpen将指向函数的指针作为第三个参数。这是我的回调方法:

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

它可以编译并与连接的 USB MIDI 设备一起使用。但是,当我按下 MIDI 设备上的某个键时,出现以下错误:

../../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
Run Code Online (Sandbox Code Playgroud)

这是什么意思?我该怎么做才能使用 MIDI 数据调用我的回调?

Hal*_*mus 5

Dart 3.1 引入了NativeCallable.listener,它可用于创建允许本机代码从任何线程调用 Dart 代码的回调。仅void支持函数。

这是示例的修订版本,现在包含NativeCallable.listener

final Pointer<HMIDIIN> hMidiDevice = malloc();

final nativeCallable = NativeCallable<MidiInProc>.listener(midiInCallback);

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

// Don't forget to close the callback when it is no longer needed.
// Otherwise, the Isolate will be kept alive indefinitely.
nativeCallable.close();
Run Code Online (Sandbox Code Playgroud)