I've got a Rust library with the following usual structure:
Cargo.toml
src
|--lib.rs
.cargo
|--config (specifies target=asmjs-unknown-emscripten)
target
|......
When I do cargo build
, I get a new directory under target called asmjs-unknown-emscripten
, but the .js files that I'd expect are not there.
As this user notes, you've got to do something special to export functions to asm.js besides marking them public:
Basically you have this boilerplate right now:
#[link_args = "-s EXPORTED_FUNCTIONS=['_hello_world']"] extern {} fn main() {} #[no_mangle] pub extern fn hello_world(n: c_int) -> c_int { n + 1 }
Then you can use this in your javascript to access and call the function:
var hello_world = cwrap('hello_world', 'number', ['number']); console.log(hello_world(41));
However, Rust complains about the #[link_args...]
directive as deprecated. Is there any documentation out there that can explain how this works?
Very interesting question! I was running into similar dependency issues with fable.
I have checked Compiling Rust to your Browser - Call from JavaScript, Advanced Linking - Link args and How to pass cargo linker args however was not able to use
cargo
in the same way asrustc --target asmjs-unknown-emscripten call-into-lib.rs
.The closer I was able to get was to run both
cargo
andrustc
likesee the so-41492672-rust-js-structure. It allows to have several libraries that compile together to the JavaScript in the final application.
I still think some manual linking would help. Would be interested to know.
P.S. to see what
rustc
uses to link, you can pass-Z print-link-args
to it.