Chr*_*Poe 5 javascript emscripten reactjs react-native
我目前正在使用Emscripten将基本的C函数编译为JavaScript,以在React Native项目中使用。但是,当我Module从React代码内部导入时,Module对象为空。这在React和React Native项目中都会发生。
index.js在我的终端上运行会node ./index.js返回预期结果。
我正在编译ping.c并使用以下命令输出ping.js:
emcc ping.c -o ping.js -s WASM=0 -s EXPORTED_FUNCTIONS='["_pingIt"]'
ping.c:
#include <stdio.h>
#include <emscripten.h>
EMSCRIPTEN_KEEPALIVE
int pingIt() {
return 1;
}
Run Code Online (Sandbox Code Playgroud)
index.js:
let Module = require('./ping.js');
module.exports = Module;
Run Code Online (Sandbox Code Playgroud)
我正在从中导出Module index.js并将其导入到我的React代码中。
// Running in React
console.log(Module); // returns {}
Run Code Online (Sandbox Code Playgroud)
// Running in React
console.log(Module._pingIt()); // should return 1
Run Code Online (Sandbox Code Playgroud)
我碰到一个偶然MODULARIZE的Emscripten文档设置在这里。我编辑了emcc命令:
emcc ping.c -o ping.js -s WASM=0 -s ENVIRONMENT=web -s EXTRA_EXPORTED_RUNTIME_METHODS='["cwrap"]' -s MODULARIZE=1
Run Code Online (Sandbox Code Playgroud)
MODULARIZE=1 成为魔术师
现在在index.js文件中:
let Module = require('./ping.js'); // Your Emscripten JS output file
let pingIt = Module().cwrap('pingIt'); // Call Module as a function
module.exports = pingIt;
Run Code Online (Sandbox Code Playgroud)
现在,您可以在React组件中import pingIt from '<file-location>';像调用其他函数一样调用该函数pingIt()。
希望有人觉得这有用!我找不到许多在React上结合使用Emscripten的示例。