Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compile a Rust project to Wasm without using wasm-pack?

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?

like image 426
RAbraham Avatar asked Apr 01 '20 21:04

RAbraham


People also ask

Is Rust Wasm faster than JS?

Wasm is 1.15-1.67 times faster than JavaScript on Google Chrome on a desktop. Wasm is 1.95-11.71 times faster than JavaScript on Firefox on a desktop.


1 Answers

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.
like image 121
Frxstrem Avatar answered Oct 23 '22 09:10

Frxstrem