New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do you send text from js to Rust? #1

Open
jakedeichert opened this Issue Dec 29, 2017 · 4 comments

Comments

3 participants
@jakedeichert
Owner

jakedeichert commented Dec 29, 2017

No description provided.

@koute

This comment has been minimized.

koute commented Dec 29, 2017

<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>

@alvaro-cuesta

This comment has been minimized.

alvaro-cuesta commented Dec 29, 2017

@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

This comment has been minimized.

koute commented Dec 29, 2017

@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.

@jakedeichert

This comment has been minimized.

Owner

jakedeichert commented Dec 29, 2017

@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 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment