WebAssembly之js調用c/c++代碼

安裝emscripten

windows系統 建議採用wsl安裝比較方便;

示例

test.c:

#include <stdio.h>
#include <emscripten/emscripten.h>

int EMSCRIPTEN_KEEPALIVE myFunction(int argc, char **argv)
{
	printf("這是一個測試函數\n");
	return 0;
}

編譯: 會生成test.js test.wasm;(詳細編譯命令看官網)

 emcc   test.c   -o   test.js 

html調用:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    window.onload = function () {
      // 初始化模塊後的調用
      Module.onRuntimeInitialized = function () {
        _myFunction();
      }
    }
  </script>
  <script async type="text/javascript" src="test.js"></script>
</body>

</html>

nodejs調用:

ex.js:

let testModule = require('./test.js');
testModule.onRuntimeInitialized = function () {
  testModule._myFunction();
}
node   ex.js

相關網址:

emscripten官網
opencv.js; (一個通過emscripten編譯opencv的js庫 )

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章