1 回答

TA貢獻1851條經(jīng)驗 獲得超3個贊
我在這個Github Repo的幫助下解決了這個問題。這就像在服務內部創(chuàng)建一個公共變量一樣簡單,并且在加載 WASM 時,將導出的 WASM 函數(shù)設置為該變量,以便可以從服務外部調用它們。對于下面的示例,我添加了一個小的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 關注
- 85 瀏覽
添加回答
舉報