如何将 WASM 正确集成到 Angular 服务中

我将一些WASM代码(从Go代码编译)集成到Angular中以使用一些函数。目前,这仅在一个地方完成,因此不会在整个应用程序中共享。我刚刚对WASM和Go使用了“标准”程序:


let go = new Go();


WebAssembly.instantiateStreaming(fetch('mywasm.wasm'), go.importObject).then((res) => {

  go.run(res.instance);


  myCoolWasmFunction();

});

但是,我想在应用程序的多个部分中执行WASM,因此尝试将其移动到服务中。我能够使用RxJS主题并在该函数之后监听“执行请求”,但我无法将任何内容返回到应用程序的其他部分。go.run(...)


基本上,我正在寻找一种干净且可用的方法来执行 Angular 应用程序中由 wasm 公开的不同函数。我是否应该将 wasm 的东西放入 其中,并创建一个只调用这些“全局可用”函数的服务?如何启用 angular 来识别它们,只需使用文件即可?index.html.d.ts


胡子哥哥
浏览 69回答 1
1回答

皈依舞

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

相关分类

Go