wasabia / flutter_gl

cross-platform call OpenGL API by Dart through dart:ffi. Provides OpenGL with Texture Widget on Flutter.
247 stars 62 forks source link

TODO use NativeFinalizer free NativeArray pointer when garbage collected #16

Open wasabia opened 2 years ago

wasabia commented 2 years ago

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

GZGavinZhao commented 2 years ago

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

  1. https://github.com/dart-lang/language/issues/1862#issuecomment-923739031
  2. https://github.com/dart-lang/sdk/issues/47270
GZGavinZhao commented 2 years ago

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没有任何性能上的影响,使用它仅仅是为了满足静态类型。