use std::ffi::CString;
use std::os::raw::c_char;
#[no_mangle]
pub extern "C" fn getWelcomeMessage() -> *mut c_char {
CString::new("Hello from Rust!")
.unwrap()
.into_raw()
}
*mut c_char
CString::new(s)
.unwrap()
.into_raw()
#[no_mangle]
pub extern "C" fn dealloc_str(ptr: *mut c_char) {
unsafe {
let _ = CString::from_raw(ptr);
}
}
const module = results.instance.exports;
let pointer = module.getWelcomeMessage();
let message = copyCStr(module, pointer);
document.getElementById("container").textContent = message;
function copyCStr(module, ptr) {
let orig_ptr = ptr;
function* collectCString() {
let memory = new Uint8Array(module.memory.buffer);
while (memory[ptr] !== 0) {
if (memory[ptr] === undefined) { throw new Error("Tried to read undef mem") }
yield memory[ptr]
ptr += 1
}
}
const buffer_as_u8 = new Uint8Array(collectCString())
const utf8Decoder = new TextDecoder("UTF-8");
const buffer_as_utf8 = utf8Decoder.decode(buffer_as_u8);
module.dealloc_str(orig_ptr);
return buffer_as_utf8
}
#![feature(proc_macro, wasm_custom_section, wasm_import_module)]
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
format!("Hello, {}!", name)
fn greet(name: &str) -> String
js_sys::JsString
gulp.task("build", async () => {
const options = { lto: true, opt_level: 's', debug: true };
const data = await Service.compileFile(project.getFile("src/main.rs"), "rust", "wasm", options);
const outWasm = project.newFile("out/main.wasm", "wasm", true);
outWasm.setData(data);
});
build.ts
Service.compileFile(project.getFile("src/main.rs"), "rust", "wasm", options);
⏬
Service.compileFileWithBindings(project.getFile("src/main.rs"), "rust", "wasm", options);
gulp.task("build", async () => {
const options = { lto: true, opt_level: 's', debug: true };
const data = await Service.compileFileWithBindings(project.getFile("src/main.rs"), "rust", "wasm", options);
const outWasm = project.newFile("out/main.wasm", "wasm", true);
outWasm.setData(data.wasm);
const outJs = project.newFile("out/main_bindings.js", "javascript", true);
outJs.setData(data.wasmBindgenJs);
});
<body>
<span id="container"></span>
<script src="../out/main_bindings.js"></script>
<script src="./main.js"></script>
</body>
const { greet } = wasm_bindgen;
function showGreeting() {
const greeting = greet('JSConf Asia');
document.getElementById("container").textContent = greeting;
}
wasm_bindgen('../out/main.wasm')
.then(showGreeting)
.catch(console.error);
const { greet } = wasm_bindgen;
wasm_bindgen('../out/main.wasm')
#[wasm_bindgen]
extern {
fn alert(s: &str);
}
#[wasm_bindgen]
extern {
fn alert(s: &str);
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
#[wasm_bindgen(js_namespace = console, js_name = log)]
fn console_log_u32(n: u32);
}