Skip to content
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
jacobdeichert opened this issue Dec 29, 2017 · 4 comments
Open

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

jacobdeichert opened this issue Dec 29, 2017 · 4 comments
Labels

Comments

@jacobdeichert
Copy link
Owner

No description provided.

@koute
Copy link

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

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

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.

@jacobdeichert
Copy link
Owner Author

@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
Labels
Projects
None yet
Development

No branches or pull requests

3 participants