Ever wondered how to pass rich data types such as structs between a TypeScript and Rust WebAssembly module? Our Principal Software Engineer Arend van Beelen has all the insights.
For starters, you need to be able to pass fat pointers between the TypeScript and Rust WebAssembly module.
A fat pointer can be a u64 that indicates both the 32-bit offset where the data starts as well as the total length of the data. In TypeScript, it can be represented using a BigInt.
Unfortunately, you can’t point this fat pointer directly to your data in Rust. That causes trouble with vectors and other indirection. You want to serialize your data with something like msgpack.org, and then pass a pointer to the serialized data. That works great going from Rust to TypeScript, but what about the other way around?
The fat pointer can only point to memory belonging to the WebAssembly module, but when we pass from TypeScript to Rust, how does TypeScript know which memory to use?
To solve this, the WebAssembly needs to expose memory allocation functions, such as malloc() and free(). These are well-known from the world of C, but unlike their C counterparts, these will work with fat pointers.
Now, whenever TypeScript needs to pass complex data to the Rust WebAssembly, it:serializes the DataSource.calls malloc() to get the memorycopies the datapasses the fat pointer to a Rust functionAnd finally, someone calls free().Found this interesting?For more updates follow us on Twitter.