(WebAssembly)JS/微信小程序,调用C/C++

JS调用C库函数

1、将.c文件编译成WebAssembly,具体步骤参考:编译 C/C++ 为 WebAssembly - WebAssembly | MDN,这个比较简单,文章中比较详细的步骤

2、编译后生成3个文件:一个.js,一个.wasm,一个.html,其中.js、.wasm不用做修改,.html文件中做了2处改动

新增button,用于触发事件

<button class="mybutton">运行我的函数</button>

调用c函数代码,其中get_device_type就是c目标函数

document.querySelector('.mybutton').addEventListener('click', function(){
  console.log('检查控制台');
  var result = Module.ccall('get_device_type', // name of C function
                             null, // return type
                             null, // argument types
                             null); // arguments
  // alert(result);
  console.log(result)
});

3、调用结果如下:

注:3个文件需要部署到服务器中才能正常运行,如nginx、tomcat等(都放到同一级目录中)。

微信小程序调用C库函数

这类资料少,花了点时间才跑通,话不多说,整活:

1、本质上也是js调用c库函数,但微信小程序有他自己的一套东西,要做一些修改和适配,相比上面js直接调用麻烦一些,首页还是将.c文件编译成WebAssembly

重点来了:打开微信开发者工具,我的版本1.06,调试基础库:2.27.1(网上有的说基础库用2.14.0,我也试了,没解决我的问题)

2、pages同级创建workers目录,将上面编译好的.js文件放里面,我的是app_client.js

 3、为了适配微信小程序,需要修改app_client.js,共5处都写到一起了

1、文件最底部导出Module
module.exports = {
  Module: Module
}

2、注释
// scriptDirectory = self.location.href

3、修改胶水js中instantiateArrayBuffer函数
function instantiateArrayBuffer(receiver) {
		return WXWebAssembly.instantiate('/pages/index/app_client.wasm', info)
			.then(function(instance) {
				return instance;
			})
			.then(receiver, function(reason) {
				err('failed to asynchronously prepare wasm: ' + reason);

				// Warn on some common problems.
				if (isFileURI(wasmBinaryFile)) {
					err('warning: Loading from a file URI (' + wasmBinaryFile + ') is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing');
				}
				abort(reason);
			})
		// return getBinaryPromise().then(function(binary) { return WebAssembly.instantiate(binary, info) }).then(receiver, function(reason) {
		//     err("failed to asynchronously prepare wasm: " + reason);
		//     abort(reason)
		// })
	}

4、修改胶水js中receiveInstance函数
wasmTable = new WXWebAssembly.Table({ "initial": 1577, "maximum": 1577 + 0, "element": "anyfunc" });

5、将胶水js中所有WebAssembly修改为WXWebAssembly

4、workers目录创建index.js,用于调用app_client.js

关键代码:cv_debug.Module._get_device_type

const cv_debug = require('app_client.js');
console.log('cv_debug', cv_debug);

setTimeout(() => {
  var zz = {};
  var v = cv_debug.Module._get_device_type('192.168.88.1',zz)//调用c函数
  console.log("zz=",zz);
  console.log('v=',v);
  worker.postMessage({
    msg: v
  })
}, 1000);

worker.onMessage(function (msg) {
  // processing of workder
  console.log(msg);

  worker.postMessage({
    msg: 'result of worker666888'
  })
})

5、/pages/index目录下index.js内容如下:用于调用workers目录下的index.js

const app = getApp()

Page({
  data: {
    message:'hello'
  },
  onLoad() {
    var _this = this;
    var worker_func = function() {
      const worker = wx.createWorker('workers/index.js', {
        // useExperimentalWorker: true
      })
      worker.postMessage({msg:'msg from main'});
      worker.onMessage(function (m) {
        console.log(m)
        _this.setData({
          message: m.msg
        })
      })
    }
    
    setTimeout(worker_func, 200);
  },
})

6、不要忘记把第1步生成的.wasm文件拷贝到/pages/index目录中,对应第3步第3点中实例化.wasm文件的路径

 7、app.json中增加配置:"workers": "workers"

 8、人狠话不对,OK了

  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值