【问题标题】:Store Rust's struct instantiated in JS in Rust's vector on the wasm side将 JS 中实例化的 Rust 结构存储在 Wasm 端的 Rust 向量中
【发布时间】:2019-12-06 03:29:08
【问题描述】:

如何将 JS 实例化的对象存储在 Rust 的结构中并对其进行计算?

我基于tutorial创建了一个示例。

生锈部分:

#[wasm_bindgen]
pub struct Body {
    position: f32
}

#[wasm_bindgen]
impl Body {
    pub fn new() -> Body {
        Body {
            position: 0.
        }
    }
}

#[wasm_bindgen]
pub struct World {
    bodies: Vec<Body>,
}

#[wasm_bindgen]
impl World {
    // .. new etc
    pub fn add_body(&mut self, object: Body) {
        self.bodies.push(Body);
    }

    pub fn step(&mut step) {
        // do something with bodies
    }
}

const world = World.new();
const body = Body.new()

console.log('body', body);
world.add_body(body);
console.log('after added', body);

body 被添加到世界后,它立即失去了它的引用。

Console.log 结果:

body Body {ptr: 1118264}
index.js:28 after added Body {ptr: 0}

是否可以将引用存储在 JS 中?我的用例:我在 JS 端处理所有交互等,在 wasm 端只处理繁重的计算。

【问题讨论】:

    标签: rust webassembly wasm-bindgen


    【解决方案1】:

    当您运行 add_body 时,它会将值的所有权传递给您的 World,然后立即将其移入 vec.如果您在 rust 中想象同样的代码:

    let mut world = World::new();
    let body = Body::new();
    
    println!("body: {:?}", body);
    world.add_body(body);
    println!("body added: {:?}", body);
    

    在第二个 println 上编译失败,因为它在 add_body 调用中被移动。

    如果您的对象主要存在于 JS 领域,您应该将它们作为 JsValue 引用在 rust 领域使用。以下是 Array 全局绑定的示例,您可以将其用作参考:https://rustwasm.github.io/wasm-bindgen/api/src/js_sys/lib.rs.html#127

    【讨论】:

      猜你喜欢
      • 2020-07-18
      • 1970-01-01
      • 2021-09-15
      • 2021-11-24
      • 1970-01-01
      • 2021-08-18
      • 2021-10-07
      • 2015-03-06
      相关资源
      最近更新 更多