webAssembly 编译c方法到js | 一见知得 | Mr J Blog

webAssembly 编译c方法到js

Mr J 22943 0

安装

git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
./emsdk install latest
./emsdk activate latest
source ./emsdk_env.sh

sign.c 代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "md5.c"
#include <emscripten.h>

char res[32] = {0};
EMSCRIPTEN_KEEPALIVE
char* sign(char * method, char * path, char * t)
{
    return "xoxoxoxoxoxo";
}

编译

emcc sign.c -o sign.js -s MODULARIZE=1 -s 'EXPORTED_FUNCTIONS=["_sign"]' -s 'EXPORTED_RUNTIME_METHODS=["ccall"]'

js中调用

var factory = require('@/wasm/sign.js')
factory().then((instance) => {
  var s = instance.ccall('sign', // name of C function
   'string', // return type
   ['string', 'string', 'string'], // argument types
   ['POST', '/x/x/x/x/x/x', '222636336']) // direct calling works
 console.log(s)
}
发表评论
表情 图片 链接 代码

分享
微信
微博
QQ