js calls c/cpp functions - Introduction to WebAssembly

1. Environment




 

Reference website: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly

http://kripken.github.io/emscripten-site/

 

2. Introduction to WebAssembly

WebAssembly is an experimental code. It is a binary file with a .wasm suffix. You can compile c/cpp into a wasm file through emcc, and then realize the interaction between cpp and js through WebAssembly.instantiate(bufferSource, importObject).

 

3. Write c/cpp files

One way to export the cpp function is to surround it with extern "C" {}

main.cpp implements the random function generator that js calls cpp

 

#include<stdio.h>
#include <random>
#include <iostream>
#include <atomic>
#include <math.h>
using namespace std;  

extern "C" {
mt19937  engine;
void setSeed(long seed)
{
	engine.seed(seed);
}

double mtrandom() {
	double min = 0.0;
	double max = 1.0;
	uniform_real_distribution<double> distribution(min, max);
	double d = distribution(engine);
	return d;
}

}

 

 

4. Compile

Using emcc can be compiled into pure js mode, or wasm format, where the wasm file is compiled

 

emcc main.cpp -o index.html -s EXPORTED_FUNCTIONS="['_setSeed','_mtrandom']" -s WASM=1

 EXPORTED_FUNCTIONS specifies the export function, WASM specifies the generated wasm format

 

5. Write script to call cpp function

index.html

<!doctype html>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>js calling cpp function example</title>
  </head>
  <body>  
	种子:<input id="seedInput" type="number" value="123456" /><br>
	数量:<input id="numInput" type="number" value="20" /><br>
	<button onclick="run1()" >cwrap call</button><button onclick="run2()" >direct call</button>
	<div id="log">
	</div>
    <script type='text/javascript'>   
	  function run1()
	  {
		var fun1=Module.cwrap('setSeed');
		var fun2=Module.cwrap('mtrandom');
		var seed=parseInt(seedInput.value);
		var num=parseInt(numInput.value);
		fun1(seed);
		log.innerHTML="";
		for(var i=0;i<num;i++)
		{
			log.innerHTML+=fun2()+"<br>";
		}
	  }
	  function run2()
	  {
		var seed=parseInt(seedInput.value);
		var num=parseInt(numInput.value);
		_setSeed(seed);//Global function
		log.innerHTML="";
		for(var i=0;i<num;i++)
		{
			log.innerHTML+=_mtrandom()+"<br>";
		}
	  }
    </script>
    <script async type="text/javascript" src="index.js"></script>
  </body>
</html>

 

 js calls the cpp method, one can use the cwarp method, and the other can use the underscore _ plus the cpp function name

 

6. Output results



 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326473432&siteId=291194637