废话不多说
首先 我们主要会用到 Emscripten生成的.wasm
大家先按照这个网址把环境塔好
https://blog.csdn.net/cgs1999/article/details/109032278
上述网址会让我们用emcc.bat 命令 C++生成.wasm 文件 可以先动手试试
然后 我们还会用到webassembly 微信叫WXWebassembly ,这个链接是认识webassembly的基础我个人感觉不错https://quickapp.vivo.com.cn/webassembly/
上代码
- 首先C++模块
自己创建hello.h hello.cpp
#include "hello.h"
#include <stdio.h>
extern "C" {
int addAll(int times) {
int n = 0;
for (int i = 0; i < times; ++i) {
n += i;
};
return n;
}
int addAll2(int times) {
int n = 0;
for (int i = 0; i < times; ++i) {
n += i+1;
};
return n;
}
int addAll3(int times) {
int n = 0;
for (int i = 0; i < times; ++i) {
n += i+2;
};
return n;
}
}
这里是我定义了三个同样的方法函数名不同,
重点:生成微信可以用的.wasm 要用下面这条命令行
emcc -O3 -s "EXPORTED_FUNCTIONS=['_addAll', '_addAll2',_addAll3]" -o 输出目录\hello.wasm 输入目录\hello.cpp --no-entry
生成出来.wasm后备用
2. Unity C# 写一个脚本接口 DllInterface.cs
public class DllInterface
{
[DllImport("__Internal")]
public static extern void HelloSS();
}
这个是封装的接口方法 在Unity工程里就可以直接用 DllInterface.Helloss();
3. 在Unity工程 Plugins目录下,自己创建个目录,我自己创建为Webgl,Webgl目录下创建一个以.jslib为结尾的文件 我这边名为 __Internal.jslib
mergeInto(LibraryManager.library, {
HelloSS: function () {
console.log("hello js ");
GameGlobal.CallJS.loadWasmFile((result)=>{
console.log(result.instance.exports.addAll(100));
})
},
});
4.在Unity工程目录下WX-WASM-SDK-V2\Runtime\wechat-default 创建 calljs.js
export const CallJS = {
hellojs: function () {
console.log("hello js`1111111111111111111")
},
loadWasmFile: function (callback) {
var info= {};
WXWebAssembly.instantiate('wasm/hello.wasm',info)
.then((result) => {
console.log("C++++++++++++++++++++",info);
console.log("Cresult",result);
console.log(result.instance.exports.addAll(10));
console.log(result.instance.exports.addAll2(10));
console.log(result.instance.exports.addAll3(10));
callback(result)
})
.catch(e => console.log("初始化失败" + e));
}
}
在同目录找到 game.js game.json 配置 calljs.js
game.js里配置以下:
import './weapp-adapter';
import unityNamespace from './unity-namespace';
import './$GAME_NAME.wasm.framework.unityweb';
import './unity-sdk/index.js';
import checkVersion from './check-version';
import 'texture-config.js';
import { launchEventType, scaleMode } from './plugin-config';
import {CallJS} from './calljs' // 引入自定义JS调用代码
GameGlobal.managerConfig = managerConfig;
GameGlobal.CallJS = CallJS; // 挂载
game.json配置 wasm目录
"wasm":
{
"code":"wasm/hello.wasm"
},
"plugins": {
"UnityPlugin": {
"version": "1.2.11",
"provider": "",
"contexts": [
{
"type": "isolatedContext"
}
]
},
把上面第一步生成好的hello.wasm拷贝到同目录下
wasm/hello.wasm
这样GameGlobal.CallJS.loadWasmFile 方法就会成功调用
上述工作完成后 基本就实现了互通了,利用Unity小游戏插件转成 微信小游戏工程后,wasm目录自动会在小游戏目录下
需要注意的是:
Unity小游戏插件时不时会提示更新,如果更新后会把game.json 和game.js覆盖掉,我们自己定义的calljs.js和wasm目录 不会被覆盖,要提前备份一下,覆盖后再重新填写上去。
总结:webassembly 方法不只是前端可以用,后端如果想用到C++算法 也可以用 也是转成.wasm并实例化,具体还要看相关文档,目前本人还没测试过发布到手机上性能怎么样。