Last active
January 26, 2018 01:57
-
-
Save asaaki/9ed680246773c955685371c20dcd0dfb to your computer and use it in GitHub Desktop.
parcel.js/Rust: return a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
gist is: return a ref to c_char and the length of it (via 2 functions) | |
C example: https://wasdk.github.io/WasmFiddle//?w590f | |
*/ | |
use std::ffi::CString; | |
use std::os::raw::c_char; | |
static HELLO: &'static str = "hello from rust"; | |
#[no_mangle] | |
pub fn get_hello() -> *mut c_char { | |
let s = CString::new(HELLO).unwrap(); | |
s.into_raw() | |
} | |
#[no_mangle] | |
pub fn get_hello_len() -> usize { | |
HELLO.len() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
based on: https://stackoverflow.com/a/47676844/653173 | |
So you can exchange numbers and strings. | |
And strings could be used to transport serialized JSON, | |
which leads to structs (serde). So you could already cover a lot. | |
when build with parcel using Rust becomes that easy: | |
*/ | |
import { memory, get_hello, get_hello_len } from "./hello.rs"; | |
const offset = get_hello(); | |
const stringBuffer = new Uint8Array(memory.buffer, offset, get_hello_len()); | |
let str = ""; | |
for (let i = 0; i < stringBuffer.length; i++) { | |
str += String.fromCharCode(stringBuffer[i]); | |
} | |
// example: output to a div: | |
let div = document.getElementById('console'); | |
div.innerText = str; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment