function-references
function-references copied to clipboard
Function reference from JavaScript functions?
I was under the impression that this proposal would allow JavaScript functions to be stored in function tables and returned as a result of a call to an import. I can't locate the appropriate changes to the JS-API spec that would accomodate this; specifically.
I don't know whether the omission was intentional or not, but this proposal does not allow that. It would have to change to "create a host function" from ToWebAssemblyValue when the destination type is a typed function reference.
So, how is someone expected to dynamically pass a callback to wasm?
Use the not-yet-standard WebAssembly.Function or create a tiny WebAssembly module that imports and re-exports the function. The re-exported function can be put in the table.
Here's where we do this in Emscripten: https://github.com/emscripten-core/emscripten/blob/af763a9099fcf1511e889057759de8cf8907db07/src/library_addfunction.js#L97-L137
We should really fix this in the spec, although it won't help the Emscripten case because Emscripten's function table holds untyped funcref.
There is no implicit conversion for function references, you'll have to use WebAssembly.Function. That is the only way I am aware to reliably provide the necessary Wasm type information to make it callable from inside Wasm. A table may well have type funcref, which is not sufficient.
We could presumably add a hack to the API to make the call to WA.Function implicit in the special case that the table (or a global?) has a concrete function type, but it won't work in general. But the discontinuity this creates seems dubious to me – it essentially violates subtyping if something works at a subtype, but can break clients when weakening(!) an input type to a supertype like funcref where it doesn't.