1 回答
TA贡献1851条经验 获得超3个赞
我在这个Github Repo的帮助下解决了这个问题。这就像在服务内部创建一个公共变量一样简单,并且在加载 WASM 时,将导出的 WASM 函数设置为该变量,以便可以从服务外部调用它们。对于下面的示例,我添加了一个小的typescript接口,以使其与类型安全一起使用:
因此,在 WASM 服务中可能如下所示:
private Suite: WasmSuite; // Here the exported functions are stored after wasm was initiated
/*
WasmSuite is defined like this:
type MyFunctionInterface = (input: string) => string;
interface WasmSuite {
myFunction: MyFunctionInterface;
}
*/
// This is just to let components know when WASM is ready
public ready: BehaviorSubject<boolean> = new BehaviorSubject(false);
constructor() {
// Init wasm, then update the ready state
this.init().then(_ => {
this.ready.next(true);
});
}
private async init() {
let go = new Go();
return WebAssembly.instantiateStreaming(
fetch('assets/main.wasm'),
go.importObject
).then((res) => {
go.run(res.instance);
// Set the Suite to an object containing the functions. The casting of the function is somewhat optional, but I think it's good practice.
this.Suite = {
myFunction: my_exported_func as MyFunctionInterface,
// "my_exported_func" is what I exported in Go via js.Global().Set("my_exported_func", js.FuncOf(myGoFunc))
};
});
}
public callMyFunction(input: string) {
// I like to publish methods to components instead of the suite object, so this is just an "interface" between callers and WASM.
return this.Suite.myFunction(input);
}
- 1 回答
- 0 关注
- 68 浏览
添加回答
举报