多个wasm之间的交互

emcc编译出两个wasm文件,想要之间互相交互
1.add.c 被调用的c文件

#include <stdlib.h>
#include <stdio.h>
int add(int a,int b){
    return a+b;
}
int addtest(){
    return 2*2;
}

编译成thisadd.wasm

emcc add.c -Os -s WASM=1 -s SIDE_MODULE=1 -s "EXPORTED_FUNCTIONS=['_add','_addtest']" -s BINARYEN_ASYNC_COMPILATION=0 -o thisadd.wasm

2.调用add.c的文件test.c

#include <stdio.h>
#include <stdlib.h>
int add(int a,int b);
int thistest(){
    return 2*4;
}
struct Node {
  int id;
  int categoryId;
  float rawAmount;
  float cookedAmount;
  struct Node *next;
  struct Node *prev;
};
int testadd(){
    return add(2,5);
}
int testnode(){
    struct Node *newNode = (struct Node *) malloc(sizeof(struct Node));
    newNode->id = 124;
    printf("newnode before:%d \n",newNode->id);
    //free(newNode);//不能用free
//    printf("newnode after:%d \n",newNode->id);
    return  newNode->id;
}
//int main(){
//    testnode();
//}

编译成thismain.wasm

emcc test.c -Os -s WASM=1 -s SIDE_MODULE=1 -s "EXPORTED_FUNCTIONS=['_thistest','_testnode','_testadd']" -s BINARYEN_ASYNC_COMPILATION=0 -o thismain.wasm

3.使用这两个thismain.wasm和thisadd.wasm的html

<!doctype html>
<html lang="en-us">
<head>
  <title>No Glue Code</title>
  <script type="application/javascript" src="../../common/load-wasm.js"></script>
</head>
<body>
  <h1>No Glue Code</h1>
  <canvas id="myCanvas" width="255" height="255"></canvas>
  <div style="margin-top: 16px;">
    <button id="actionButton" style="width: 100px; height: 24px;">
      Pause
    </button>
  </div>
  <script type="application/javascript">
    const canvas = document.querySelector('#myCanvas');
    const ctx = canvas.getContext('2d');

    const env = {
      table: new WebAssembly.Table({ initial: 8, element: 'anyfunc' }),
      __memory_base:0
    };
    const fetchAndCompileModules = () =>
      Promise.all(
        ['thismain.wasm', 'thisadd.wasm'].map(fileName =>
          fetch(fileName)
            .then(response => {
              if (response.ok) return response.arrayBuffer();
              throw new Error(`Unable to fetch WebAssembly file: ${fileName}`);
            })
            .then(bytes => WebAssembly.compile(bytes))
        )
      );
    async function initializeWasm() {
        const wasmMemory = new WebAssembly.Memory({ initial: 1024 });
        const [compiledMain, compiledAdd] = await fetchAndCompileModules();

        const addInstance = await WebAssembly.instantiate(compiledAdd, { env });
        const instantiateMain = (compiledMain, addInstance, wasmMemory) => {
            const addMethods = addInstance.exports;
            return WebAssembly.instantiate(compiledMain, {
              env: {
                __memory_base:0,//add by hao
                __table_base: 0,
                memory: wasmMemory,
                table: new WebAssembly.Table({ initial: 16, element: 'anyfunc' }),
                abort: console.log,
                _consoleLog: value => console.log(value),
                _add: addMethods._add,//add by hao
                _printf:console.log
                //_free: memoryMethods.free
              }
            });
        }
        const mainInstance = await instantiateMain(
            compiledMain,
            addInstance,
            wasmMemory
        );
        console.log("addInstance:"+addInstance.exports._addtest());
        console.log("mainInstance:"+mainInstance.exports._thistest());
        console.log("mainInstance.testnode:"+mainInstance.exports._testnode());
        console.log("mainInstance.testadd:"+mainInstance.exports._testadd());

        //return mainInstance.exports;
    }
    initializeWasm();
  </script>
</body>
</html>

main.c 里面通过WebAssembly.instantiate的env参数
把add.c 的 _add 方法传入进去,就可以互相调用了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值