sdk
sdk copied to clipboard
Converting FFI Handle to Dart Object
When using FFI to load a function that has a handle in the signature, you can either put Handle
in the signature, or Pointer<Void>
. If you use Handle
, the FFI trampoline will automatically convert the C Dart_Handle
to a Dart Object
. If you use Pointer<Void>
, you'll just get an opaque value that is C compatible.
I have a use case where I want to put a Dart_PersistentHandle
to a Dart Function
in a C struct. I used FFI to load Dart_NewPersistentHandle
and Dart_DeletePersistentHandle
. I loaded Dart_NewPersistentHandle
as void*(Handle)
so I could pass in an Object
and get back something I could stick in the struct, and loaded Dart_DeletePersistentHandle
as void(void*)
so I could delete the handle later.
But I also wanted to get the Function
out of the C struct so I could call it, and I couldn't find a way of converting the Pointer<Void>
that was the Dart_PersistentHandle
to a Dart Object
. My hacky work around was to load another copy of Dart_NewPersistentHandle
and Dart_DeletePersistentHandle
, this time as Handle(void*)
and void(Handle)
, so I could use the generated trampolines to do the conversion.
Context: https://github.com/dart-lang/ffigen/issues/381#issuecomment-1194456759
@dcharkes How hard would it be to add a util to package:ffi
that can convert Dart_Handle
etc to a Dart Object
?
@liamappelbe could you provide some code snippets to illustrate the problem?