defineProperty method
在 JS 对象上定义一个方法,该方法执行时会回调 Dart 函数
Implementation
void defineProperty(String name, Function callback) {
if (_disposed || _token.isDisposed) return;
final key = "${context.handle.address}_$name";
if (_callbacks.containsKey(key)) {
_callbacks[key] = callback;
return;
}
// 注册 C 侧蹦床函数
final trampoline = Pointer.fromFunction<NativeAsyncTypedCallHandler>(
_jsNativeCallTrampoline,
);
final fnRes = context.ffi.newFunction(context.handle, name, trampoline);
context.ffi.setProperty(context.handle, _handle, name, fnRes);
// 保存回调以防止被 Dart GC,并用于静态方法查找
_callbacks[key] = callback;
// newFunction 返回的 JSValue (fnRes) 引用计数为 1
// setProperty 会调用 JS_DupValue,导致引用计数 +1
// 因此我们需要释放 fnRes 持有的引用,否则会导致内存泄漏
context.ffi.freeValue(context.handle, fnRes);
context.ffi.freeQjsResult(fnRes);
}