Rust in browser: generate wasm on the fly, call function

High level problem:

  1. I have a piece of Rust code that is compiled to wasm32 and running in the browser.

  2. Inside the browser, I want to generate wasm32 code on the fly, and call it, passing it float* or int*

  3. Previously, there were claims that this is not possible due to wasm32 not being designed for jit / dynamic code generation.

  4. However, if I'm reading Is it possible to do dynamic linking in WebAssembly with Rust? - Stack Overflow correctly, the following is possible:

4a. from rust running in browser/wasm32: generate some wast/wasm32 on the fly

4b. load the wasm32 module, sharing the 'address space' (i.e. something like a dlopen)

4c. call functions in the new module

===

If the above is true, does anyone have an example of doing this in Rust ?

1 Like

So conceptually I don't see why you couldn't compile a rust compiler to wasm and use some javascript glue code to load your new on the fly compiled wasm modules. Practically I can't imagine this being an appropriate solution for your task. If you want a general purpose Rust compiler you'd have to send hundreds of megabytes just for that functionality. Are you asking this out of general curiosity, or do you have some specific problem you want to solve?

1 Like

Ah, I should clarify, I'm not asking for, at runtime, a "rustc -> wasm" compiler.

I'm asking for a "some restricted set of instructions -> wasm" dynamic code generator. Even a "c -> wasm" or "mips -> wasm" or "sorta x86 -> wasm" would be fine. The part I need is all the glue that takes the wast, loads it as a module, dynamically loads it, and calls the function ...

Searching for 'tiny wasm compiler' I found this GitHub - maierfelix/mini-c: C to WebAssembly compiler which seems promising, the example https://maierfelix.github.io/mini-c/ does if I understand correctly, exactly what you want.

Definitly doable, but you will have to glue them together with some JS, just like wasm-bindgen allows you to call JS Objects.

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