jacobdeichert/wasm-astar

How do you send text from js to Rust?

Opened this issue · 4 comments

How do you send text from js to Rust?
koute commented

<shameless plug>

Using the stdweb crate:

let string = "Foo";
let result: String = js! {
    console.log("Rust -> JS:", @{string});
    return "Bar";
}.try_into().unwrap();

println!("JS -> Rust: {}", result);

(:

Although I'm sure speed-wise there's room for improvement here, so right now if you need absolutely highest performance doing it manually is probably what you want.

</shameless plug>

@koute how does that work under the hood?

AFAIK JS can export Memory objects to WASM, but from a quick glance I didn't find Rust code that actually uses JS exported memory (only the one that Rust exports), so I'm not sure what's the API for the FFI there (if any).

Another approach I thought of is to ask Rust to allocate memory from JS, write the string there and pass the pointer to Rust.

koute commented

@alvaro-cuesta In a nutshell the Rust code tells the JavaScript the address of the string, and then JS code accesses the memory object exported by the webassembly module and decodes the string. As for sending a string from JS to Rust the JS code calls malloc, copies the string into the newly allocated chunk of memory, and gives a pointer to that memory to Rust which then assumes the ownership of it.

@koute thanks for explaining how the js > rust scenario works! I figured there was a way, just didn't research it yet.

Also, great work with stdweb. I've been keeping my eye on it 👍