生锈 - 在WASM外部功能中共享状态
我正在创建一个带有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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论