我有一个用 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));
});
关于typescript - 如何将 WebAssembly 函数导入 TypeScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56646799/