[英]How to import WebAssembly functions to TypeScript?
我有一個用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));
});
這是一種使用AssemblyScript Loader的方法,您可以直接在TypeScript中使用它:
它需要“ regenerator-runtime”:“ ^ 0.13.2” ,您可以將其與加載程序一起導入到要使用Wasm模塊的.ts文件中,例如:
import { instantiateStreaming, ASUtil } from 'assemblyscript/lib/loader';
import { regeneratorRuntime } from 'regenerator-runtime';
我已經實例化了:
interface MyApi {
add(a: number, b: number): number;
}
async function getWasm(): Promise<ASUtil & MyApi> {
const imports: any = {};
let module: ASUtil & MyApi = await instantiateStreaming<MyApi>(fetch('path/to/file.wasm'), imports);
return module;
}
之后,您可以簡單地:
getWasm().then((module) => {
console.log('The result is: ', module.add(3, 4));
});
以及使用加載程序提供的任何其他功能:
let str = "Hello World!";
let ref = module.__retain(module.__allocString(str));
console.log(module.__getString(ref));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.