webassembly: Register PyProxy objects for JS-side finalisation.

And clear the corresponding `proxy_c_ref[c_ref]` entry when the finaliser
runs.  This then allows the C side to (eventually) garbage collect the
corresponding Python object.

Signed-off-by: Damien George <damien@micropython.org>
This commit is contained in:
Damien George
2024-05-21 11:42:51 +10:00
parent 5c7a414574
commit 57a9ffa632
3 changed files with 38 additions and 1 deletions

View File

@@ -61,6 +61,11 @@ class PythonError extends Error {
function proxy_js_init() {
globalThis.proxy_js_ref = [globalThis, undefined];
globalThis.proxy_js_ref_next = PROXY_JS_REF_NUM_STATIC;
globalThis.pyProxyFinalizationRegistry = new FinalizationRegistry(
(cRef) => {
Module.ccall("proxy_c_free_obj", "null", ["number"], [cRef]);
},
);
}
// js_obj cannot be undefined
@@ -251,6 +256,7 @@ function proxy_convert_mp_to_js_obj_jsside(value) {
const target = new PyProxy(id);
obj = new Proxy(target, py_proxy_handler);
}
globalThis.pyProxyFinalizationRegistry.register(obj, id);
}
return obj;
}