生锈 - 在WASM外部功能中共享状态

发布于 2025-02-05 07:13:46 字数 1023 浏览 2 评论 0原文

我正在创建一个带有Rust和Wasm-Bindgen的简单应用程序。我希望能够从JavaScript调用初始化函数,调用函数以从Rust程序控制状态,然后通过函数从状态获得一个值。我无法通过整个结构,它不是线程安全的或能够序列化的。 这是我想尝试使用懒惰静态和其他一些技巧来创建全局变量的简化示例

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,
}

,但我无法弄清楚。

最终我最终得到了这个。这是不安全的,但是似乎有效的

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,
}

方法可以安全地做这件事吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文