Skip to content

Instantly share code, notes, and snippets.

@asaaki
Last active January 26, 2018 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asaaki/9ed680246773c955685371c20dcd0dfb to your computer and use it in GitHub Desktop.
Save asaaki/9ed680246773c955685371c20dcd0dfb to your computer and use it in GitHub Desktop.
parcel.js/Rust: return a string
/*
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()
}
/*
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