我按照这里的简单示例将rust结构导出到React TypeScript应用程序:
#[wasm_bindgen]
pub struct Foo {
contents: u32,
}
#[wasm_bindgen]
impl Foo {
#[wasm_bindgen(constructor)]
pub fn new() -> Foo {
Foo { contents: 0 }
}
pub fn get_contents(&self) -> u32 {
self.contents
}
}
然后我在App.tsx
中添加以下
function App() {
let f = new Foo();
[...]
然而,当我运行react应用程序时,我会得到:未捕获类型错误:无法读取未定义(读取"foo_new"(的属性
结构体在module.js
中导出为:
export class Foo {
static __wrap(ptr) {
const obj = Object.create(Foo.prototype);
obj.ptr = ptr;
return obj;
}
__destroy_into_raw() {
const ptr = this.ptr;
this.ptr = 0;
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_foo_free(ptr);
}
/**
*/
constructor() {
const ret = wasm.foo_new(); <--- fails here
return Foo.__wrap(ret);
}
/**
* @returns {number}
*/
get_contents() {
const ret = wasm.__wbg_get_player_id(this.ptr);
return ret >>> 0;
}
}
在module.d.ts
中为:
export class Foo {
free(): void;
/**
*/
constructor();
/**
* @returns {number}
*/
get_contents(): number;
}
我错过了什么?
我遇到了与您相同的错误。Uncaught TypeError: Cannot read properties of undefined (reading 'foo_new')
错误表示您的WASM库未加载。在阅读了WASM bindgen生成的.js文件后,我注意到wasm
对象需要初始化,这可以通过init
函数来完成。此外,已导出init
函数。
export { initSync }
export default init;
因此,问题的解决方案是在使用Foo
之前,通过init
函数初始化wasm
对象。
假设Rust项目的名称是rust_wasm
,我执行以下操作:
- 导入函数
import rust_wasm_init from "rust_wasm";
import {Foo} from "rust_wasm";
- 运行函数
async run_wasm_funcion() {
const path_to_wasm = "https://localhost:3000/static/js/rust_wasm.wasm"; //Remember to update the parameter in CopyPlugin
await rust_wasm_init(path_to_wasm); //This initializes the wasm object mentioned above
const foo = new Foo();
console.log(foo.get_contents());
}