Rust - Sharing state in wasm extern functions

Viewed 217

I'm creating a simple app with rust and wasm-bindgen. I want to be able to call the initialize function from javascript, call functions to control the state from the rust program, and then get a value from the state with a function. I cannot pass the entire struct, it isn't thread safe or able to be serialized. Here's a simplified example of what I would want

use wasm_bindgen::prelude::*
#[wasm_bindgen]
pub fn initialize_state(value: i32) {
    state = State { a_value: value };
}

#[wasm_bindgen]
pub fn increment_value() {
    state.a_value += 1;
}
#[wasm_bindgen]
pub fn get_value() -> i32 {
    state.a_value
}

struct State {
    a_value: i32,
}

I tried using lazy static and some other tricks to create a global variable for this, but I couldn't figure it out.

Eventually I ended up with this. It's unsafe, but it seems to work

use wasm_bindgen::prelude::*;

static mut STATE: *mut State = std::ptr::null_mut::<State>();

#[wasm_bindgen]
pub fn initialize_state(value: i32) {
    unsafe {
        STATE = Box::leak(Box::new(State { a_value: value }));
    }
}

#[wasm_bindgen]
pub fn increment_value() {
    unsafe {
        (*STATE).a_value += 1;
    }
}
#[wasm_bindgen]
pub fn get_value() -> i32 {
    unsafe { (*STATE).a_value }
}

struct State {
    a_value: i32,
}

Is there a way of doing this safely?

0 Answers
Related