如何将字符串传递给使用 emscripten 为 WebAssembly 编译的 C 代码

How to pass a string to C code compiled with emscripten for WebAssembly

我一直在寻找 WebAssembly 网站和教程,但感觉有点迷茫。

我有以下 C 代码:

void EMSCRIPTEN_KEEPALIVE hello(char * value){
    printf("%s\n", value);
}

我编译它(我也不确定这部分是最好的方法):

emcc demo.c -s WASM=1 -s NO_EXIT_RUNTIME=1 -o demo.js

据我了解,我现在可以在我的 javascript class 中使用 demo.js 胶水代码并以这种方式调用方法:

...
<script src="demo.js"></script>
<script>
    function hello(){        
        // Get the value 
        var value = document.getElementById("sample");
        _hello(value.innerHTML);
    }
</script>
...

当我调用该方法时,我在控制台中看到的打印内容是:

(null)

我是否缺少将字符串值传递给使用 WebAssembly 编译的 C 代码的内容?

非常感谢

我实际上找到了问题的答案。我只需要使用 Emscripten 在 'Glue' 代码中自动构建的函数,当您将 C++ 代码构建到 WASM 时也会生成这些代码。

所以基本上,要将字符串传递给使用 Emscripten 编译为 WebAssembly 的 C++ 代码,您只需这样做:

// Create a pointer using the 'Glue' method and the String value
var ptr  = allocate(intArrayFromString(myStrValue), 'i8', ALLOC_NORMAL);

// Call the method passing the pointer
val retPtr = _hello(ptr);

// Retransform back your pointer to string using 'Glue' method
var resValue = Pointer_stringify(retPtr);

// Free the memory allocated by 'allocate' 
_free(ptr);   

有关 Emscripten's page 的更多完整信息。