Kęstutis Ramulionis
Kęstutis Ramulionis

Reputation: 290

Flutter Dart DynamicLibrary on separate thread (Isolate) can't be called

I have application written on Flutter (Dart) and I have integrated FFI library. I need to call a method from that library on a separate Isolate but it gives me a following error:

Unhandled Exception: Invalid argument(s): Illegal argument in isolate message: (object is a DynamicLibrary)

Here is my code:

class Hub {
  static final Hub _singleton = Hub._internal();

  late hub lib;
  late Pointer<hub_state_s> state;

  factory Hub() {
    return _singleton;
  }

  Hub._internal();
}
  start() async {
    Hub hub = Hub();
    var initResult = await hub.init();
    if (initResult == 0) {
      await Isolate.run(() {
        print("running isolate");
        hub.lib.hub_start(hub.state);
      });
    }
  }

Upvotes: 0

Views: 258

Answers (1)

rainyl
rainyl

Reputation: 21

Native resources is unsendable, see https://dart.dev/language/concurrency#message-types

start() async {
    Hub hub = Hub();
    var initResult = await hub.init();
    if (initResult == 0) {
      await Isolate.run(() {
        print("running isolate");
        hub.lib.hub_start(hub.state);
      });
    }
  }

Here you send the hub instance to isolate via closure, so the message is

Unhandled Exception: Invalid argument(s): Illegal argument in isolate message: (object is a DynamicLibrary)

As Richard said above, feel free to open a new DynamicLibrary in Isolate, as the document said

Calling this function multiple times with the same path, even across different isolates, only loads the library into the DartVM process once. Multiple loads of the same library file produces DynamicLibrary objects which are equal (==), but not identical.

Upvotes: 1

Related Questions