19

I would like to compile a Rust program/project to Wasm for use within my Python application using python-ext-wasm. The existing tutorials assume that it's for the web and suggest wasm-pack. Is there another way of just compiling Rust to Wasm without JavaScript bindings?

For example, if I have a Rust program (myproject/math.rs).

#[no_mangle]
pub extern fn sum(x: i32, y: i32) -> i32 {
    x + y
}
  1. How do I convert that into a wasm file without webpack?

  2. How do I take an entire project (with it's library dependencies) and compile all of them to Wasm?

1

1 Answer 1

22

You can compile WebAssembly directly with cargo build --target wasm32-unknown-unknown. This is essentially what other tooling like wasm-pack and wasm-bindgen are built around, and if you don't want that (e.g. if you're not targeting JavaScript) you can just use that to compile directly to WebAssembly.

Some caveats though:

  • All communication between the WebAssembly module and host must happen with extern functions. This means that there's only a limited number of types that can be used, mostly primitive types (integers, floats, booleans and pointers). You won't be able to pass complex types unless you're using an additional layer of abstraction on top (which is what wasm-bindgen does).
  • Large parts of the standard library (including file systems and networking, for instance) is not supported by the wasm32-unknown-unknown target. If your WebAssembly host supports WASI (WebAssembly System Interface), you can use the wasm32-wasi target instead to compile a module with WASI support, which supports much more of the standard library.
Sign up to request clarification or add additional context in comments.

2 Comments

They said they're targeting python-ext-wasm, which is part of a Wasmer project, which, in turn, uses and supports WASI APIs, so wasm32-wasi is the appropriate target.
@RReverser I suspected that (which is why I added it to my answer), but I couldn't find any direct references on python-ext-wasm's repostiory page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.