How To Use Emscripten Compiled Javascript Within 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
Solution 1:
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
being the magic bit
Now within the index.js
file:
letModule= require('./ping.js'); // Your Emscripten JS output fileletpingIt= Module().cwrap('pingIt'); // Call Module as a functionmodule.exports = pingIt;
Now in the React component you can import pingIt from '<file-location>';
and call the function like any other pingIt()
.
Hope someone finds this useful! I couldn't find many examples of using Emscripten alongside React.
Solution 2:
I used a slightly different approach to call the ping.c function from React Native, by defining an EXPORT_NAME
for the module and creating the module whenever it's appropriate in your code.
Using Emscripten emsdk:
emcc ping.c -o ping.js -s WASM=0 -s ENVIRONMENT=web -s MODULARIZE=1 -s "EXPORT_NAME='createPingModule'"
In the React Native component (App.tsx):
import createPingModule from'./ping';
...
createPingModule()
.then(module => {
console.log('Module created!');
let a = module._pingIt();
console.log(a);
});
Post a Comment for "How To Use Emscripten Compiled Javascript Within React / React Native"