sdk icon indicating copy to clipboard operation
sdk copied to clipboard

Converting FFI Handle to Dart Object

Open liamappelbe opened this issue 2 years ago • 1 comments

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 avatar Jul 27 '22 20:07 liamappelbe

@liamappelbe could you provide some code snippets to illustrate the problem?

dcharkes avatar Jul 31 '22 16:07 dcharkes