How to return a reference to a nested Rust struct in WebAssembly?

大兔子大兔子 提交于 2020-12-16 04:09:32

问题


I have 2 structs where I can access the Parent struct from JavaScript and create it with new:

struct Child {
    foo: String,
}

impl Child {
    pub fn do_something(&self) {
        /* some stuff */
    }
}

#[wasm_bindgen]
pub struct Parent {
    child: Child,
}

#[wasm_bindgen]
impl Parent {
    pub fn new() -> Self {
        Self {
            child: Child { foo: String::new() },
        }
    }

    pub fn child(&self) -> &Child {
        &self.child
    }
}

I cannot compile the code because of an error at the child() method:

cannot return a borrowed ref with #[wasm_bindgen]

Is there any way to get a pointer to child and access it from JavaScript? Why can Rust not return a borrowed reference to WebAssembly? Is this because JavaScript could modify its value and Rust couldn't guarantee immutability of the data?


回答1:


In WASM, Javascript is like kernel code. It runs at the highest level of privilege and has free access to the entire memory space. Some have mentioned that if Rust were to return an reference into JS, it could end up being a dangling pointer. This would be bad, but it's not Rust's problem. Like kernel code, it's Javascript's responsibility to be safe in that context. The real problem is that there would be no way to ensure the JS didn't abuse an immutable reference in order to mutate data and cause memory corruption.



来源:https://stackoverflow.com/questions/61385031/how-to-return-a-reference-to-a-nested-rust-struct-in-webassembly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!