| 1 |
# Exporting a struct to JS |
| 2 |
|
| 3 |
So far we've covered JS objects, importing functions, and exporting functions. |
| 4 |
This has given us quite a rich base to build on so far, and that's great! We |
| 5 |
sometimes, though, want to go even further and define a JS `class` in Rust. Or |
| 6 |
in other words, we want to expose an object with methods from Rust to JS rather |
| 7 |
than just importing/exporting free functions. |
| 8 |
|
| 9 |
The `#[wasm_bindgen]` attribute can annotate both a `struct` and `impl` blocks |
| 10 |
to allow: |
| 11 |
|
| 12 |
```rust |
| 13 |
#[wasm_bindgen] |
| 14 |
pub struct Foo { |
| 15 |
internal: i32, |
| 16 |
} |
| 17 |
|
| 18 |
#[wasm_bindgen] |
| 19 |
impl Foo { |
| 20 |
#[wasm_bindgen(constructor)] |
| 21 |
pub fn new(val: i32) -> Foo { |
| 22 |
Foo { internal: val } |
| 23 |
} |
| 24 |
|
| 25 |
pub fn get(&self) -> i32 { |
| 26 |
self.internal |
| 27 |
} |
| 28 |
|
| 29 |
pub fn set(&mut self, val: i32) { |
| 30 |
self.internal = val; |
| 31 |
} |
| 32 |
} |
| 33 |
``` |
| 34 |
|
| 35 |
This is a typical Rust `struct` definition for a type with a constructor and a |
| 36 |
few methods. Annotating the struct with `#[wasm_bindgen]` means that we'll |
| 37 |
generate necessary trait impls to convert this type to/from the JS boundary. The |
| 38 |
annotated `impl` block here means that the functions inside will also be made |
| 39 |
available to JS through generated shims. If we take a look at the generated JS |
| 40 |
code for this we'll see: |
| 41 |
|
| 42 |
```js |
| 43 |
import * as wasm from './js_hello_world_bg'; |
| 44 |
|
| 45 |
export class Foo { |
| 46 |
static __construct(ptr) { |
| 47 |
return new Foo(ptr); |
| 48 |
} |
| 49 |
|
| 50 |
constructor(ptr) { |
| 51 |
this.ptr = ptr; |
| 52 |
} |
| 53 |
|
| 54 |
free() { |
| 55 |
const ptr = this.ptr; |
| 56 |
this.ptr = 0; |
| 57 |
wasm.__wbg_foo_free(ptr); |
| 58 |
} |
| 59 |
|
| 60 |
static new(arg0) { |
| 61 |
const ret = wasm.foo_new(arg0); |
| 62 |
return Foo.__construct(ret) |
| 63 |
} |
| 64 |
|
| 65 |
get() { |
| 66 |
const ret = wasm.foo_get(this.ptr); |
| 67 |
return ret; |
| 68 |
} |
| 69 |
|
| 70 |
set(arg0) { |
| 71 |
const ret = wasm.foo_set(this.ptr, arg0); |
| 72 |
return ret; |
| 73 |
} |
| 74 |
} |
| 75 |
``` |
| 76 |
|
| 77 |
That's actually not much! We can see here though how we've translated from Rust |
| 78 |
to JS: |
| 79 |
|
| 80 |
* Associated functions in Rust (those without `self`) turn into `static` |
| 81 |
functions in JS. |
| 82 |
* Methods in Rust turn into methods in wasm. |
| 83 |
* Manual memory management is exposed in JS as well. The `free` function is |
| 84 |
required to be invoked to deallocate resources on the Rust side of things. |
| 85 |
|
| 86 |
To be able to use `new Foo()`, you'd need to annotate `new` as `#[wasm_bindgen(constructor)]`. |
| 87 |
|
| 88 |
One important aspect to note here, though, is that once `free` is called the JS |
| 89 |
object is "neutered" in that its internal pointer is nulled out. This means that |
| 90 |
future usage of this object should trigger a panic in Rust. |
| 91 |
|
| 92 |
The real trickery with these bindings ends up happening in Rust, however, so |
| 93 |
let's take a look at that. |
| 94 |
|
| 95 |
```rust |
| 96 |
// original input to `#[wasm_bindgen]` omitted ... |
| 97 |
|
| 98 |
#[export_name = "foo_new"] |
| 99 |
pub extern "C" fn __wasm_bindgen_generated_Foo_new(arg0: i32) -> u32 { |
| 100 |
let ret = Foo::new(arg0); |
| 101 |
Box::into_raw(Box::new(WasmRefCell::new(ret))) as u32 |
| 102 |
} |
| 103 |
|
| 104 |
#[export_name = "foo_get"] |
| 105 |
pub extern "C" fn __wasm_bindgen_generated_Foo_get(me: u32) -> i32 { |
| 106 |
let me = me as *mut WasmRefCell<Foo>; |
| 107 |
wasm_bindgen::__rt::assert_not_null(me); |
| 108 |
let me = unsafe { &*me }; |
| 109 |
return me.borrow().get(); |
| 110 |
} |
| 111 |
|
| 112 |
#[export_name = "foo_set"] |
| 113 |
pub extern "C" fn __wasm_bindgen_generated_Foo_set(me: u32, arg1: i32) { |
| 114 |
let me = me as *mut WasmRefCell<Foo>; |
| 115 |
wasm_bindgen::__rt::assert_not_null(me); |
| 116 |
let me = unsafe { &*me }; |
| 117 |
me.borrow_mut().set(arg1); |
| 118 |
} |
| 119 |
|
| 120 |
#[no_mangle] |
| 121 |
pub unsafe extern "C" fn __wbindgen_foo_free(me: u32) { |
| 122 |
let me = me as *mut WasmRefCell<Foo>; |
| 123 |
wasm_bindgen::__rt::assert_not_null(me); |
| 124 |
(*me).borrow_mut(); // ensure no active borrows |
| 125 |
drop(Box::from_raw(me)); |
| 126 |
} |
| 127 |
``` |
| 128 |
|
| 129 |
As with before this is cleaned up from the actual output but it's the same idea |
| 130 |
as to what's going on! Here we can see a shim for each function as well as a |
| 131 |
shim for deallocating an instance of `Foo`. Recall that the only valid wasm |
| 132 |
types today are numbers, so we're required to shoehorn all of `Foo` into a |
| 133 |
`u32`, which is currently done via `Box` (like `std::unique_ptr` in C++). |
| 134 |
Note, though, that there's an extra layer here, `WasmRefCell`. This type is the |
| 135 |
same as [`RefCell`] and can be mostly glossed over. |
| 136 |
|
| 137 |
The purpose for this type, if you're interested though, is to uphold Rust's |
| 138 |
guarantees about aliasing in a world where aliasing is rampant (JS). |
| 139 |
Specifically the `&Foo` type means that there can be as much aliasing as you'd |
| 140 |
like, but crucially `&mut Foo` means that it is the sole pointer to the data |
| 141 |
(no other `&Foo` to the same instance exists). The [`RefCell`] type in libstd |
| 142 |
is a way of dynamically enforcing this at runtime (as opposed to compile time |
| 143 |
where it usually happens). Baking in `WasmRefCell` is the same idea here, |
| 144 |
adding runtime checks for aliasing which are typically happening at compile |
| 145 |
time. This is currently a Rust-specific feature which isn't actually in the |
| 146 |
`wasm-bindgen` tool itself, it's just in the Rust-generated code (aka the |
| 147 |
`#[wasm_bindgen]` attribute). |
| 148 |
|
| 149 |
[`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html |