如何在React / React Native中使用Emscripten编译的JavaScript [英] How to use Emscripten compiled JavaScript within React / React Native
问题描述
我目前正在使用Emscripten将基本C函数编译成JavaScript以在React Native项目中使用。但是,当我从React代码中导入 Module
时,Module对象为空。这在React和React Native项目中都会发生。
I'm currently using Emscripten to compile a basic C function into JavaScript to use within a React Native project. However, when I import Module
from inside React code, the Module object is empty. This occurs in both React and React Native projects.
在我的终端中运行 index.js
code> node ./index.js 返回预期结果。
Running index.js
in my terminal with node ./index.js
returns the expected result.
我正在编译ping.c和使用以下命令输出ping.js:
I'm compiling ping.c and outputting ping.js with this command:
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;
}
index.js:
let Module = require('./ping.js');
module.exports = Module;
我从中导出模块index.js
并将其导入我的React代码。
I'm exporting Module from index.js
and importing it into my React code.
// Running in React
console.log(Module); // returns {}
预期行为
Expected behavior
// Running in React
console.log(Module._pingIt()); // should return 1
推荐答案
我偶然发现了<$ cms c中的MODULARIZE 设置这里。我编辑了 emcc
命令:
I stumbled across a MODULARIZE
setting in the Emscripten docs here. I edited the emcc
command:
emcc ping.c -o ping.js - s WASM = 0 -s ENVIRONMENT = web -s EXTRA_EXPORTED_RUNTIME_METHODS ='[cwrap]'-s MODULARIZE = 1
MODULARIZE = 1
是神奇的位
现在在 index.js
file:
let Module = require('./ping.js'); // Your Emscripten JS output file
let pingIt = Module().cwrap('pingIt'); // Call Module as a function
module.exports = pingIt;
现在在React组件中,您可以从'< file-导入pingIt location>';
并像调用其他任何 pingIt()
一样调用该函数。
Now in the React component you can import pingIt from '<file-location>';
and call the function like any other pingIt()
.
希望有人觉得这很有用!我找不到很多使用Emscripten和React的例子。
Hope someone finds this useful! I couldn't find many examples of using Emscripten alongside React.
这篇关于如何在React / React Native中使用Emscripten编译的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!