Skip to content

How to create longer-lived objects in Wasm that would outlive Wasm function scope, but not completely static ? In JS heap #3728

Answered by Liamolucko
artem-tim asked this question in Q&A
Discussion options

You must be logged in to vote

The easy solution to this is to use Closure::forget (or Closure::into_js_value) and set WASM_BINDGEN_WEAKREF=1 when running wasm-bindgen, which does exactly what you said: making the closure live in the JS heap and get deallocated by the GC. If you don't set WASM_BINDGEN_WEAKREF though, Closure::forget just leaks memory, since doing this requires the 'weak references' proposal (specifically FinalizationRegistry). It's been supported by all browsers for a while now, but wasm-bindgen still has it disabled by default because apparently some serverless runtimes don't (see #3384).

Alternatively, you can manually deallocate the Closure inside flush like this:

pub async fn my_wasm_response_proce…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@artem-tim
Comment options

Answer selected by artem-tim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants