[英]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类中使用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”代码中自动构建的函数,这些代码也是在向WASM构建C ++代码时生成的。
所以基本上,要将一个String传递给使用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页面的更完整信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.