WebAssembly之js调用c/c++代码

安装emscripten

windows系统 建议采用wsl安装比较方便;

示例

test.c:

#include 
#include 

int EMSCRIPTEN_KEEPALIVE myFunction(int argc, char **argv)
{
	printf("这是一个测试函数\n");
	return 0;
}

编译: 会生成test.js test.wasm;(详细编译命令看官网)

 emcc   test.c   -o   test.js 

html调用:


<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Documenttitle>
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库 )

你可能感兴趣的:(nodejs,html)