Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[vm/ffi] Introduce a Pointer<T extends Struct>.refWithFinalizer(finalizer, token) #56796

Open
dcharkes opened this issue Sep 27, 2024 · 2 comments
Labels
area-native-interop Used for native interop related issues, including FFI. library-ffi

Comments

@dcharkes
Copy link
Contributor

It's quite common to want to return a struct from Dart code using dart:ffi and having a call with the pointer inside that code (dart-lang/native#1601, dart-lang/native#1480 (comment)).

That currently requires the following dance:

  1. calloc a Pointer<MyStruct>
  2. cast the struct to <Uint8>
  3. call asTypedList with calloc.nativeFree as finalizer
  4. call Struct.create<MyStruct> with the typed data

Maybe we could simplify step 2 to 4 by introducing:

/// Extension on [Pointer] specialized for the type argument [Struct].
@Since('2.12')
extension StructPointer<T extends Struct> on Pointer<T> {
  /// A Dart view of the struct referenced by this pointer.
  ///
  /// Attaches [finalizer] to the backing store of the struct.
  /// The pointer (`this`) must _not_ be used anymore if the struct is _not_ guaranteed to be kept alive.
  /// Prefer doing any native calls with the pointer _before_ calling `refWithFinalizer`.
  ///
  /// Reading [ref] creates a reference accessing the fields of this struct
  /// backed by native memory at [address].
  /// The [address] must be aligned according to the struct alignment rules of
  /// the platform.
  ///
  /// Assigning to [ref] copies contents of the struct into the native memory
  /// starting at [address].
  ///
  /// This extension method must be invoked on a receiver of type `Pointer<T>`
  /// where `T` is a compile-time constant type.
  external T refWithFinalizer(Pointer<NativeFinalizerFunction>? finalizer, @Since('3.1') Pointer<Void>? token);
@dcharkes dcharkes added library-ffi area-native-interop Used for native interop related issues, including FFI. labels Sep 27, 2024
@codesculpture
Copy link
Contributor

Hey @dcharkes , what's Pointer<Void> token for ?

@dcharkes
Copy link
Contributor Author

dcharkes commented Oct 1, 2024

See https://api.flutter.dev/flutter/dart-ffi/NativeFinalizer/attach.html documentation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-native-interop Used for native interop related issues, including FFI. library-ffi
Projects
None yet
Development

No branches or pull requests

2 participants