我一直在看WebAssembly网站和教程,我觉得有点迷路了。
我有以下C代码:
void EMSCRIPTEN_KEEPALIVE hello(char * value){
printf("%sn", value);
}
我用编译了它(我也不确定这部分是最好的方法):
emcc demo.c -s WASM=1 -s NO_EXIT_RUNTIME=1 -o demo.js
据我所知,我现在可以在javascript类中使用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页面的更多完整信息。