如何在 React / React Native 中使用 Emscripten 编译的 JavaScript

IT技术 javascript reactjs react-native emscripten
2021-05-23 04:54:19

我目前正在使用 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;
}

索引.js:

let Module = require('./ping.js');

module.exports = Module;

我正在从中导出moduleindex.js并将其导入到我的 React 代码中。

当前行为

// Running in React
console.log(Module); // returns {}

预期行为

// Running in React
console.log(Module._pingIt()); // should return 1
2个回答

MODULARIZE此处的 Emscripten 文档中偶然发现了一个设置我编辑了emcc命令:

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文件中:

let Module = require('./ping.js'); // Your Emscripten JS output file
let pingIt = Module().cwrap('pingIt'); // Call Module as a function

module.exports = pingIt;

现在在 React 组件中,您可以import pingIt from '<file-location>';像调用任何其他pingIt().

希望有人觉得这很有用!我找不到很多将 Emscripten 与 React 结合使用的示例。

我使用了一种稍微不同的方法从 React Native 调用 ping.c 函数,通过EXPORT_NAME为module定义一个并在代码中适当的时候创建module。

使用 Emscripten emsdk:

emcc ping.c -o ping.js -s WASM=0 -s ENVIRONMENT=web -s MODULARIZE=1 -s "EXPORT_NAME='createPingModule'"

在 React Native 组件(App.tsx)中:

import createPingModule from './ping';

...

createPingModule()
  .then(module => {
    console.log('Module created!');
    let a = module._pingIt();
    console.log(a);
});