Wasm: Return pointer from function (GC)

How to expose a Go API that accepts and returns pointers (to structs) without the need to pass the underlying structs to JavaScript (converting them to JS values)?

Context: I have a Go library that operates on tree structures (traverse, mutate). The functions in the library accept and return only pointers to these structs. How to expose such API to JS? JS doesn’t need access to the actual structs, it only needs references to pass them between the exposed functions; all the operations are done by Go in the wasm instance. Example usage of the exposed API:

const t = Tree() // pointer to struct in wasm instance
Traverse(t, function(n) {
    // traverse/mutate nodes
})

My current solution is to pass the pointers to JS and back using the unsafe.Pointer type. But as Go can’t track these pointers in JS, garbage collection reclaims the memory. I tested this by creating trees until triggering the GC and by using the runtime.GC(). To prevent GC reclaiming “live” memory, I created a global slice in which I store pointers to structs I don’t want garbage collected. By testing the same way as before, it seems to be working, but I don’t like the approach and don’t know whether it is really safe or correct.

2 Likes

@touchmarine can you share a snippet of your workaournd?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.