首页  >  问答  >  正文

将 JS 函数传递给 WASM

我正在读一本关于 WebAssembly 的好书,我正在尝试学习如何在不使用“胶水代码”的情况下将 JS 函数导入 wasm

这是 C 文件,其中声明了 2 个 extern 函数

extern int jsClearRect();
extern int jsFillRect();

然后,我使用以下说明将 c 代码编译为 wasm

emcc src/main.c -Os -s STANDALONE_WASM=1 -s SIDE_MODULE=1  -o main.wasm

然后我被指示编写一个JS脚本,其中instantiate wasm文件,定义jsFillRect()jsClearRect()并使用导入对象将它们导入到模块的env中。

// define the import Objects
const importObj = {
    "env": {
        "__memory_base":0,
        "tableBase":0,
        "memory": new WebAssembly.Memory({ initial: 256 }),
        "table": new WebAssembly.Table({ initial: 8, element: 'anyfunc' }),
        jsClearRect(): function() {/*function definition here*/},
        jsFillRect(): function() {/*function definition here*/},
    }
}
// import the module
fetch('main.wasm')
        .then(obj => WebAssembly.instantiateStreaming(obj,importObject))
        .then(result => console.log(result))
        .catch(err => console.log(err))

我收到一个错误:

TypeError: import object field 'GOT.mem' is not an Object

我在这里展示的导入对象已经是原始对象的修改版本(您可以在此处找到)。在此示例中,函数在 JS 中声明为 _jsClearRect(),但模块找不到 jsClearRect() 的定义。然后它找不到 __memory_base 的定义,因为它被声明为 memoryBase 但现在我不知道 Object 的国王代表 GOT.mem​​

我环顾四周,感觉我正在使用旧的 API,但我找不到合适的解决方案来实现这一点。

所以我的问题是:

如何将 Javascript 函数导入到 wasm 模块中?

P粉081360775P粉081360775204 天前297

全部回复(1)我来回复

  • P粉276876663

    P粉2768766632024-03-30 09:04:48

    GOT.mem​​ 来自 emscripten 使用的动态链接 ABI。在这种情况下,我认为您不需要动态链接内容,您可以/应该删除 -sSIDE_MODULE

    这应该简化/减少您需要提供的导入。 (例如,您不需要提供 tablememory)。

    回复
    0
  • 取消回复