Skip to content

TODO use NativeFinalizer free NativeArray pointer when garbage collected #16

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

Open
wasabia opened this issue May 29, 2022 · 2 comments
Open

Comments

@wasabia
Copy link
Owner

wasabia commented May 29, 2022

https://api.dart.cn/stable/2.17.0/dart-ffi/NativeFinalizer-class.html

@wasabia wasabia changed the title TODO use NativeFinalizer auto free NativeArray pointer when garbage collected TODO use NativeFinalizer free NativeArray pointer when garbage collected May 29, 2022
@GZGavinZhao
Copy link

另:我看不出来你的代码里有没有用,我发现 dart-lang/language#1862 中提出了两个方案能在C和Dart之间传送各种体积大的array的时候减少内存占用并优化性能:

  1. How to pass huge objects across isolates and/or ffi, without huge memory and cpu footprint? dart-lang/language#1862 (comment)
  2. provide helpers (or samples) for zero-overhead non-leaking bytes transfer between isolates in ffi dart-lang/sdk#47270

@GZGavinZhao
Copy link

GZGavinZhao commented Sep 4, 2022

Hi,我又回来啦~ 以前一直对NativeFinalizer一头雾水,最近花了点时间在自己的代码里试验了一下搞明白它的用法,一些小心得希望能有所帮助:

// filename: lib/src/utils/memory.dart

/// A generic [NativeFinalizer] to free any pointer by calling the C function
/// `free`. It's kind of like a workaround to combat the restriction of
/// [NativeFinalizer] (which only accepts a C function, not a Dart
/// function).
final freenalizer = NativeFinalizer(DynamicLibrary.executable().lookup('free'));

使用方法大概是:

import 'dart:ffi';
import 'package:mypackage/src/utils/memory.dart';

class Foo extends Finalizable {
  Pointer<X> _ptr = calloc();
  Foo() {
    freenalizer.attach(this, _ptr.cast());
  }
}

应用到你这里可能就是将这一行加上一个freenalizer.dispose(this, data.cast()),之后因为PlatformNativeArray的所有child class的constructor里你好像都有用super(),所以理论上dispose()就可以完全丢掉啦。

注:据我所知cast没有任何性能上的影响,使用它仅仅是为了满足静态类型。

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

No branches or pull requests

2 participants