Skip to content
This repository has been archived by the owner on Jan 17, 2024. It is now read-only.

[Feature] use like function for temporory native malloc/calloc object #86

Closed
Sunbreak opened this issue Mar 3, 2021 · 6 comments
Closed

Comments

@Sunbreak
Copy link

Sunbreak commented Mar 3, 2021

It is quit easy to forget to free memory from toNativeUtf8 and toNativeUtf16

Sunbreak/logic_conf.dart@956ac5a

-    var descriptor = _libc.open2(path.toNativeUtf8().cast(), O_RDWR);
+    var nativeUtf8 = path.toNativeUtf8();
+    var descriptor = _libc.open2(nativeUtf8.cast(), O_RDWR);
+    malloc.free(nativeUtf8);

Could we have some Kolin's use-like statement?

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/use.html

FileWriter("test.txt")
  .use { w -> w.write("something") }

Or similiar ones:

@Sunbreak
Copy link
Author

Sunbreak commented Mar 3, 2021

@dcharkes
Copy link
Contributor

dcharkes commented Mar 3, 2021

Hey, please take a look at the Pool: https://github.com/dart-lang/sdk/blob/master/samples/ffi/resource_management/pool_sample.dart#L24-L31

  // To ensure resources are freed, wrap them in a [using] call.
  using((Pool pool) {
    final p = pool<Int64>(2);

    // Do something with p.

    // p is automatically `free`d at the end of this scope.
  });

Your could would probably be something such as:

final descriptor = using((Pool pool) {
  final nativeUtf8 = path.toNativeUtf8(pool);
  return _libc.open2(nativeUtf8.cast(), O_RDWR);
}

Please let me know if you find that sample useful, I could merge it to this package.

@Sunbreak
Copy link
Author

Sunbreak commented Mar 3, 2021

It helps a lot. Sunbreak/logic_conf.dart#8

I'll appreciate if we could merge Pool to package:ffi

@Fox32
Copy link

Fox32 commented May 25, 2021

Done by #103?

@dcharkes
Copy link
Contributor

Indeed.

@hacker1024
Copy link

Is this documented anywhere? I had to go searching through issues to find this feature. I didn't think to look at the API reference because the README points to another website.

Perhaps a brief overview of the features provided by this package could be added to the README?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

4 participants