Wasm extern reference types

Is it at all possible currently to write Rust code which uses wasm externref with the current compiler (nightly allowed, bindgens allowed)?

I suppose in the extreme you could write wasm shims for any imports/exports using externref which inserts an extra indirection stashing them in a table and only passing around indices internally, which are just plain u32 and can be worked with easily. Do wasm-bindgen or wit-bindgen support automating application of that shim?

If I understand correctly, externref can't be stored in linear memory in wasm (because their size is fully unknown), so the table indirection is necessary. rustc already does this for funcref types, but I guess that the difference there is that the funcref table can be pregenerated, as the set of functions turned into reference is known statically, whereas the table of externref grows indefinitely (one for each passed in) and garbage collecting it is difficult.

I wonder if it could ever be possible to write Rust code manipulating opaque reference types directly... the problem AIUI is that taking a reference &ExternRef just plainly requires putting the value into linear memory, so even ?DynSized, extern type, and unsized function parameters aren't enough; you need what'd perhaps be called ?Pointee to prevent taking a reference at all. It unfortunately seems like wasm reference types are unfortunately just a little too foreign to be directly used in Rust unless W3C decides to walk back reference types' opaqueness and allow them to be stored in linear memory.

Rust is going to have interesting issues with multiple memories too if it can't handle a non-linear memory space. My understanding is that should be fine according to the memory model it inherited from C, the only thing you can do with a reference is dereference, turn it into an integer, and turn that same integer back into the reference, same type and everything.

Since it's unsound to cast through an integer (except when it's not), I think that integer doesn't even need to be unique with a memory, and can be simply the table index (though in practice it's more likely a separate address space is allocated)

Wit-bindgen doesn't afaik. Wasm-bindgen does. See Support for Reference Types - The `wasm-bindgen` Guide

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.