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

[ffi]Is it necessary to manually free the memory? #45689

Closed
xuexin opened this issue Apr 14, 2021 · 3 comments
Closed

[ffi]Is it necessary to manually free the memory? #45689

xuexin opened this issue Apr 14, 2021 · 3 comments
Labels
area-vm Use area-vm for VM related issues, including code coverage, and the AOT and JIT backends. library-ffi

Comments

@xuexin
Copy link

xuexin commented Apr 14, 2021

class RawImage extends Struct {
  @Int32()
  external int length;
  external Pointer<Uint8> bytes;
}

Pointer<RawImage> mallocRawImage(Uint8List bytes) {
  final bytesPointer = bytes.allocatePointer();
  final refPointer = malloc<RawImage>();
  refPointer.ref
    ..length = bytes.length
    ..bytes = bytesPointer;
  return refPointer;
}
extension Uint8ListBlobConversion on Uint8List {
  Pointer<Uint8> allocatePointer() {
    final blob = malloc<Uint8>(length);
    final blobBytes = blob.asTypedList(length);
    blobBytes.setAll(0, this);
    return blob;
  }
}

I manually malloc memory for Struct to pass it to native, should I manually free the Pointer and the Pointer? And how about the Struct returned from native?

@keertip keertip added area-vm Use area-vm for VM related issues, including code coverage, and the AOT and JIT backends. library-ffi labels Apr 14, 2021
@dcharkes
Copy link
Contributor

Hi @xuexin,

When you malloc/calloc you should malloc.free/calloc.free it.

When a struct gets returned by value it is backed by TypedData instead of Pointer and lives in the Dart heap. So in that case it is garbage collected automatically.

@dcharkes
Copy link
Contributor

I can take a look into #45697, that would enable creating structs backed by TypedData also when passing them as arguments.

Of course it will take a while before that would be available in the stable Dart release, so for now you need to be careful to free your allocated structs.

@xuexin
Copy link
Author

xuexin commented Apr 14, 2021

@dcharkes
Thanks for your answer

@xuexin xuexin closed this as completed Apr 14, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-vm Use area-vm for VM related issues, including code coverage, and the AOT and JIT backends. library-ffi
Projects
None yet
Development

No branches or pull requests

3 participants