Rust wasm + ReactJS: Passing object causes null pointer passed to rust error

I am using wasm_bindgen and ReactJS.

I have a struct in Rust which I have added #[wasm_bindgen] to. I can create this struct as an object in JavaScript.

However as soon as I try passing this object around in the ReactJS-land (via properties) I get the error:

null pointer passed to rust

What confuses me is that I can pass this object between normal JavaScript functions without error.

When I print the object to the console I see that it starts as having a field named ptr which has a non-zero value. But when I look at the passed version this ptr field is 0.

The ReactJS part is sort of like this:

import { React } from "react";
import { ReactDOM } from "react-dom";

import { RustObj } from "my-wasm-pkg";

function FooComponent(props) {
    props.rustObj.do_thing(); // <<< Error here, rustObj.ptr == 0

    return (<div>I have done the thing</div>);
}

function App() {
    // For this example lets say my Rust code defines
    // struct RustObj and which has a method named 
    // do_thing() + a constructor.
    var rustObj = new RustObj(); // rustObj.ptr != 0

    return (<FooComponent rustObj={rustObj} />
}

ReactDOM.render(<App />, document.getElementById("root"));

I can however pass a function which calls rustObj.do_thing() and no error occurs:

// ...
function FooComponent(props) {
    props.runDoThing();
    // ...
}

function App() {
    // ...
    const runDoThing = () => {
        rustObj.do_thing();
    };

    return (FooComponent runDoThing={runDoThing} />);
}
// ...

Why is this? What exactly is causing my object to become null?

I believe this crash was caused by my Rust method having mut self instead of &mut self.

Here is what the bad Rust code looked like:

#[wasm_bindgen]
struct RustObj {
    x: u32
}


#[wasm_bindgen]
impl RustObj {
    pub fn do_thing(mut self) { // <<< Causes error
        self.x += 3;
    }
}

When I looked at the generated JavaScript binding file (From wasm-pack build) I saw that the do_thing() JavaScript function actually set this.ptr = 0.

When I changed the Rust code to:

#[wasm_bindgen]
impl RustObj {
    pub fn do_thing(&mut self) {
// ...

The JavaScript stopped crashing, and the JavaScript function no longer set this.ptr = 0.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.