[英]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.