sdk
sdk copied to clipboard
[vm/ffi] NativeFinalizers with out parameters
Some or close/release functions have a different signature. If such signature requires extra parameters being passed in, such functions can be wrapped in a C function that takes a pointer to a helper struct that has the arguments that should be passed into the finalizer function. One such example would be HeapFree in the windows API.
However, some native finalization functions have out parameters that communicate error messages. Because native finalization functions cannot call back into Dart, the only way to communicate such information to Dart is to use an NativeCallable.listener to communicate the errors back to the isolate. Since finalizers are run async anyway, I believe this is a reasonable thing to do.
Any other ideas on how to deal with this @mkustermann? Or do you think scheduling something on the Dart event loop with NativeCallable.listener is the right thing to do?
We should probably add some documentation about how to do this.
Oh calling NativeCallable.listener from a NativeFinalizer doesn't work yet. I've filed: https://github.com/dart-lang/sdk/issues/54939.
I've made an example on how this is supposed to work in: https://github.com/dart-lang/native/tree/native-finalizer/pkgs/native_assets_cli/example/native_add_library. We can clean it up and land it as a sample later for documentation purposes.
As discussed offline with @liamappelbe and @mkustermann:
- Resources should not be freed in Dart code. (Not the use case mentioned above.) When the isolate shuts down that would lead to resources not being freed.
- Errors should not be reported via a Dart callback. (The use case above.) That would swallow error messages if the isolate is shut down. Instead the errors should be reported via whatever native error reporting API is available. For example: https://developer.android.com/reference/android/util/Log and https://developer.apple.com/documentation/os/logging.