调用c++_WebAssembly: 在C代码中调用JS的函数
生活随笔
收集整理的這篇文章主要介紹了
调用c++_WebAssembly: 在C代码中调用JS的函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
0. 前提知識點
在index.html寫測試代碼
<script>var Module = {};Module.onRuntimeInitialized = () => {// 在這個回調中調用wasm中的方法}; </script> <!-- 膠水層代碼要放在后臺 --> <script src="test.js"></script>1. 在C中調用JS函數之addFunction
Emscripten提供了多種在C環境調用JavaScript的方法,包括:
前3種方法點擊鏈接就可以查看詳細的使用說明
下面著重描述下第4種方法,主要結合Calling JavaScript functions as function pointers from C實踐一下
You can use addFunction to return an integer value that represents a function pointer. Passing that integer to C code then lets it call that value as a function pointer, and the JavaScript function you sent to addFunction will be called.你可以使用addFunction這個函數的返回值(數字)來代表這個函數的指針。然后將該指針(數字)傳遞給C代碼,然后讓其將該值作為函數指針進行調用,發送給addFunction的JavaScript函數將被調用。
由上面的說明可以推測出Module有一個addFunction的方法,返回值是一個數字類型。
在嘗試調用的時候,發現提示說要在編譯的時候導出這個函數
docker run --rm -v $(pwd):/src -u $(id -u):$(id -g) emscripten/emsdk emcc test.cc -o test.js # 要在這里加上-s EXTRA_EXPORTED_RUNTIME_METHODS="['addFunction']"再次調用時又發現要設置wasm table成為可以grow的
此時要在編譯腳本中再加上一行
-s ALLOW_TABLE_GROWTHYou should build with -s ALLOW_TABLE_GROWTH to allow new functions to be added to the table. Otherwise by default the table has a fixed size.加上編譯后,再次運行,發現叕報錯了,缺少函數簽名
查看文檔
When using addFunction on LLVM wasm backend, you need to provide an additional second argument, a Wasm function signature string. Each character within a signature string represents a type. The first character represents the return type of a function, and remaining characters are for parameter types. - 'v': void type - 'i': 32-bit integer type - 'j': 64-bit integer type (currently does not exist in JavaScript) - 'f': 32-bit float type - 'd': 64-bit float type原來是addFunction的第二個參數需要標明函數的返回值類型,及參數類型,再次修改
終于成功了,此時已得到了函數的指針,將其傳入到C代碼中就可以調用了。
下面看下C代碼的實現:
// 聲明函數簽名,在JS中調用addFunction時,第二個函數的簽名要與此聲明保持一致 typedef void testExternalJSMethod(int p);// 導出一個接收函數 EM_PORT_API (void) pass_fn_ptr(int ptr) {((testExternalJSMethod*)ptr)(1); } // js Module.onRuntimeInitialized = () => {function jsFunction(i) {console.log('定義在js中的function');console.log('從c中傳來的參數: ', i);}// 這里說明下,C語言是先聲明函數返回的類型,所以這里要先寫返回值的類型,再寫其他參數的類型var fPtr = Module.addFunction(jsFunction, 'vi');Module._pass_fn_ptr(fPtr); };最后看下輸出結果:
2. addFunction的優點
X. 參考文檔
總結
以上是生活随笔為你收集整理的调用c++_WebAssembly: 在C代码中调用JS的函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 二叉树为空意味着二叉树_程序员的进阶课-
- 下一篇: 转数组在线 php_2021年最新PHP