首页 > 解决方案 > WebAssembly 从 C 调用 JavaScript 函数作为函数指针

问题描述

我想将 JavaScript 函数作为参数传递给从 WebAssembly 导出的函数,函数指针作为参数。

考虑以下示例:

JavaScript 代码:

function foo() {
    console.log("foo");
}

wasmInstance.exports.expects_funcptr(foo);

C代码:

typedef void(*funcptr_type)(void);

void expects_funcptr(funcptr_type my_funcptr)
{
    my_funcptr();
}

我没有使用 Emscripten,但他们在“与代码交互”页面中有一个关于该主题的部分:https ://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html#interacting-with -code-call-function-pointers-from-c。他们有一个addFunction为此调用的函数。

我在这里查看了它的实现:https ://github.com/emscripten-core/emscripten/blob/incoming/src/support.js#L755

而且看起来很... hacky。看起来他们正在创建一个新的 wasm 模块,该模块将 javascript 函数作为导入并将其作为 wasm 函数导出。只有这样他们才能将函数添加到 WebAssembly 表中。

有一个更好的方法吗?

编辑

这是我目前处理这个问题的方式。通过使用以下函数将 JS 函数转换为 WASM,我可以将 JS 函数传递给 WASM,如下所示:

// How the above example would be called using the converter function.

wasmInstance.exports.expects_funcptr(convertFunction(foo, Types.VOID));

// The actual converter function (minus some details for simplicity)

function convertFunction(func, ret, params) {

    // Construct a .wasm binary by hand
    const bytes = new Uint8Array([
        0x00, 0x61, 0x73, 0x6d, // magic
        0x01, 0x00, 0x00, 0x00, // version
        // ... generate type, import, export sections as well
    ]);

    const module = new WebAssembly.Module(bytes);
    const instance = new WebAssembly.Instance(module, {
        a: {
            b: func
        }
    });

    const ret = table.length;

    table.grow(1);
    table.set(ret, instance.exports.f);

    return ret;

}

这是一个粗略的例子来展示这个概念。实际的实现会检查函数是否已被转换、处理错误等。

标签: webassembly

解决方案


函数表是 Wasm 中函数指针的原语。您将不得不使用一个函数指针。管理这个单独的地址空间可能非常棘手,emscripten 中的所有“hacky”代码都是为了确保安全完成。在您自己的代码中,您不需要像 emscripten 那样强制执行许多不变量,因此您可能可以摆脱其中的大部分。很高兴在评论中澄清这一点。


推荐阅读