| 1 |
# Exporting a function to JS |
| 2 |
|
| 3 |
Alright now that we've got a good grasp on JS objects and how they're working, |
| 4 |
let's take a look at another feature of `wasm-bindgen`: exporting functionality |
| 5 |
with types that are richer than just numbers. |
| 6 |
|
| 7 |
The basic idea around exporting functionality with more flavorful types is that |
| 8 |
the wasm exports won't actually be called directly. Instead the generated |
| 9 |
`foo.js` module will have shims for all exported functions in the wasm module. |
| 10 |
|
| 11 |
The most interesting conversion here happens with strings so let's take a look |
| 12 |
at that. |
| 13 |
|
| 14 |
```rust |
| 15 |
#[wasm_bindgen] |
| 16 |
pub fn greet(a: &str) -> String { |
| 17 |
format!("Hello, {}!", a) |
| 18 |
} |
| 19 |
``` |
| 20 |
|
| 21 |
Here we'd like to define an ES module that looks like |
| 22 |
|
| 23 |
```ts |
| 24 |
// foo.d.ts |
| 25 |
export function greet(a: string): string; |
| 26 |
``` |
| 27 |
|
| 28 |
To see what's going on, let's take a look at the generated shim |
| 29 |
|
| 30 |
```js |
| 31 |
import * as wasm from './foo_bg'; |
| 32 |
|
| 33 |
function passStringToWasm(arg) { |
| 34 |
const buf = new TextEncoder('utf-8').encode(arg); |
| 35 |
const len = buf.length; |
| 36 |
const ptr = wasm.__wbindgen_malloc(len, 1); |
| 37 |
let array = new Uint8Array(wasm.memory.buffer); |
| 38 |
array.set(buf, ptr); |
| 39 |
return [ptr, len]; |
| 40 |
} |
| 41 |
|
| 42 |
function getStringFromWasm(ptr, len) { |
| 43 |
const mem = new Uint8Array(wasm.memory.buffer); |
| 44 |
const slice = mem.slice(ptr, ptr + len); |
| 45 |
const ret = new TextDecoder('utf-8').decode(slice); |
| 46 |
return ret; |
| 47 |
} |
| 48 |
|
| 49 |
export function greet(arg0) { |
| 50 |
const [ptr0, len0] = passStringToWasm(arg0); |
| 51 |
try { |
| 52 |
const ret = wasm.greet(ptr0, len0); |
| 53 |
const ptr = wasm.__wbindgen_boxed_str_ptr(ret); |
| 54 |
const len = wasm.__wbindgen_boxed_str_len(ret); |
| 55 |
const realRet = getStringFromWasm(ptr, len); |
| 56 |
wasm.__wbindgen_boxed_str_free(ret); |
| 57 |
return realRet; |
| 58 |
} finally { |
| 59 |
wasm.__wbindgen_free(ptr0, len0, 1); |
| 60 |
} |
| 61 |
} |
| 62 |
``` |
| 63 |
|
| 64 |
Phew, that's quite a lot! We can sort of see though if we look closely what's |
| 65 |
happening: |
| 66 |
|
| 67 |
* Strings are passed to wasm via two arguments, a pointer and a length. Right |
| 68 |
now we have to copy the string onto the wasm heap which means we'll be using |
| 69 |
`TextEncoder` to actually do the encoding. Once this is done we use an |
| 70 |
internal function in `wasm-bindgen` to allocate space for the string to go, |
| 71 |
and then we'll pass that ptr/length to wasm later on. |
| 72 |
|
| 73 |
* Returning strings from wasm is a little tricky as we need to return a ptr/len |
| 74 |
pair, but wasm currently only supports one return value (multiple return values |
| 75 |
[is being standardized](https://github.com/WebAssembly/design/issues/1146)). |
| 76 |
To work around this in the meantime, we're actually returning a pointer to a |
| 77 |
ptr/len pair, and then using functions to access the various fields. |
| 78 |
|
| 79 |
* Some cleanup ends up happening in wasm. The `__wbindgen_boxed_str_free` |
| 80 |
function is used to free the return value of `greet` after it's been decoded |
| 81 |
onto the JS heap (using `TextDecoder`). The `__wbindgen_free` is then used to |
| 82 |
free the space we allocated to pass the string argument once the function call |
| 83 |
is done. |
| 84 |
|
| 85 |
Next let's take a look at the Rust side of things as well. Here we'll be looking |
| 86 |
at a mostly abbreviated and/or "simplified" in the sense of this is what it |
| 87 |
compiles down to: |
| 88 |
|
| 89 |
```rust |
| 90 |
pub extern "C" fn greet(a: &str) -> String { |
| 91 |
format!("Hello, {}!", a) |
| 92 |
} |
| 93 |
|
| 94 |
#[export_name = "greet"] |
| 95 |
pub extern "C" fn __wasm_bindgen_generated_greet( |
| 96 |
arg0_ptr: *const u8, |
| 97 |
arg0_len: usize, |
| 98 |
) -> *mut String { |
| 99 |
let arg0 = unsafe { |
| 100 |
let slice = ::std::slice::from_raw_parts(arg0_ptr, arg0_len); |
| 101 |
::std::str::from_utf8_unchecked(slice) |
| 102 |
}; |
| 103 |
let _ret = greet(arg0); |
| 104 |
Box::into_raw(Box::new(_ret)) |
| 105 |
} |
| 106 |
``` |
| 107 |
|
| 108 |
Here we can see again that our `greet` function is unmodified and has a wrapper |
| 109 |
to call it. This wrapper will take the ptr/len argument and convert it to a |
| 110 |
string slice, while the return value is boxed up into just a pointer and is |
| 111 |
then returned up to was for reading via the `__wbindgen_boxed_str_*` functions. |
| 112 |
|
| 113 |
So in general exporting a function involves a shim both in JS and in Rust with |
| 114 |
each side translating to or from wasm arguments to the native types of each |
| 115 |
language. The `wasm-bindgen` tool manages hooking up all these shims while the |
| 116 |
`#[wasm_bindgen]` macro takes care of the Rust shim as well. |
| 117 |
|
| 118 |
Most arguments have a relatively clear way to convert them, bit if you've got |
| 119 |
any questions just let me know! |
| 120 |
|