我有一个用TypeScript编写的现有项目,我正在尝试导入WebAssembly模块以替换某些功能。
通过提取将.wasm加载到.js文件的逻辑,我设法成功导入了WebAssembly模块。这是它自己的TypeScript模块,并导入到要使用WebAssembly函数的.ts文件中。
为了演示,我在wasm中做了一个简单的添加功能。
在使用AssemblyScript编译为.wasm的.ts中:
export function add(a: i32, b: i32): i32 {
return a + b;
}
在.js文件中:
export async function loadWasm() {
const imports = {}; // Omitted the contents since it's most likely irrelevant
const module = await
WebAssembly.instantiateStreaming(fetch('path/to/file.wasm'),imports);
return module;
}
在要使用WebAssembly的.ts文件中:
loadWasm().then((module: any) => {
let addFunc: ((a: number, b: number) => any) = module.add;
console.log('Adding 2 and 5 in Wasm: ' + addFunc(2, 5));
});
但是运行此命令时,出现以下错误:
Uncaught (in promise) TypeError: addFunc is not a function at eval
有谁知道是什么原因造成的?
试试以下代码片段:
loadWasm().then(module => {
const { add: addFunc } = module.instance.exports;
console.log(addFunc(2, 5));
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句