2017-10-18 148 views
0

我一直在尋找一個WebAssembly網站和教程,我感覺有點失落。如何將字符串傳遞給用emscripten編譯爲WebAssembly的C代碼

我有以下的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> 
... 

我看到的是bei吳印在控制檯當我打電話的方法是:

(null) 

有我丟失的東西傳遞一個字符串值的C代碼編譯WebAssembly?

非常感謝

+1

什麼是「hello」和「_stringify」,你在哪裏給他們打電話? – Bergi

+0

這是一個錯字,它應該是_hello(value.innerHTML),我編輯了這個問題,對不起 – ElCapitaine

+0

請注意,您必須導出函數才能夠從js調用它們:'emcc demo.c -01 -s EXPORTED_FUNCTIONS =「['_ main','_hello'] -o demo.js」'對於掙扎也不感到厭煩,這是全新的並且處於沉重的發展階段,文檔必然不完整且過時。 –

回答

1

我居然找到了一個回答我的問題。我只需使用Emscripten自動在「Glue」代碼中構建的函數,這些代碼在將C++代碼構建到WASM時也會生成。

所以基本上,傳遞一個字符串C++代碼編譯成WebAssembly與Emscripten你只是做這樣的:

// 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更爲完整的信息。

相關問題