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
jakedeichert opened this issue Dec 29, 2017 · 4 comments
Open

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

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

Comments

@jakedeichert
Copy link
Owner

@jakedeichert jakedeichert commented Dec 29, 2017

No description provided.

@koute
Copy link

@koute 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 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 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
Copy link
Owner Author

@jakedeichert 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
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
3 participants