c代码
#include <stdio.h> #include <emscripten/emscripten.h> typedef struct { int32_t number; double d; uint8_t* s; }obj; obj g = {1245,25.123456,(uint8_t*)"123456"}; uint8_t * EMSCRIPTEN_KEEPALIVE getStr(){ return (uint8_t *)"hello world"; } obj* EMSCRIPTEN_KEEPALIVE getObj(){ return &g; }
emscripten编译命令
emcc main.c -s EXTRA_EXPORTED_RUNTIME_METHODS=["UTF8ToString","getValue"] -s WASM=1 -s MODULARIZE=1 -s EXPORT_NAME="WasmModule" -s ENVIRONMENT=web -o index.js
调用代码
WasmModule().then(mod => { //获取c字符串 let strPtr = mod._getStr(); //c字符串转换为js字符串 console.log("_getStr 返回值",mod.UTF8ToString(strPtr)); //获取结构体 let obj = mod._getObj(); // int32_t number; console.log("int32_t number",mod.HEAP32[obj >> 2]) //double d; console.log("double d",mod.HEAPF64[(obj + 12) >> 3]); //uint8_t* s; console.log("uint8_t* s",mod.UTF8ToString(obj - 24)); })
输出