dart-lang / native

Dart packages related to FFI and native assets bundling.
BSD 3-Clause "New" or "Revised" License
114 stars 40 forks source link

ObjCBlock closures not registered with the objective_c `_blockClosureRegistry` in release build #1570

Open RyanHir opened 2 days ago

RyanHir commented 2 days ago

During release build, usage of the ObjCBlock listener method that is generated by the ffigen tool causes an exception to be thrown. This is not present when using a debug build.

Crash Log

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
#0      getBlockClosure (package:objective_c/src/internal.dart:346)
#1      _ObjCBlock_ffiVoid_MLModel_NSError_closureTrampoline (package:path/to/binding/binding_gen.dart:31868)
#2      ObjCBlock_ffiVoid_MLModel_NSError.listener.<anonymous closure> (package:path/to/binding/binding_gen.dart)
#3      _RootZone.runUnaryGuarded (dart:async/zone.dart:1594)
#4      _RootZone.bindUnaryCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1633)
#5      _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:184)

Code Snippet

  var completer = Completer<binding.MLModel?>();
  var handler = binding.ObjCBlock_ffiVoid_MLModel_NSError.listener(
      (binding.MLModel? model, objc.NSError? error) {
    completer.complete(model);
  });
  binding.MLModel.loadContentsOfURL_configuration_completionHandler_(
      compiledModel, config.config, handler);
  var model = await completer.future;

Versions Dart: 3.5.3 Flutter: 3.24.3 objective_c: 2.0.0 ffi: 2.1.3 ffigen: 14:0

RyanHir commented 2 days ago

For now, ffigen 13 and objective_c 1.1.0 appear to be working for me.

liamappelbe commented 2 days ago

I think the handler is being GC'd early. If so, as a workaround you could try to force the compiler to keep it alive. For example, you could store the handler in a global variable until it's invoked. @RyanHir Can you give that a try and let me know if it works? That will help me narrow down the issue.

Probably related to https://github.com/dart-lang/native/pull/1442