Call C binary from javascript WITHOUT process.exec

RMAG news

What’s this about?
I am going to directly start with an example calling a C binary from javascript and it is NOT a process.exec call.

Emscripten is what we will use, it helps us create supporting glue code to call the C binary from javascript.

What about emscripten installation?
I will make a following post on the emscripten installation.
But here is all the action, assuming we have emscripten installed and configured on our box.

Steps

Write C program
Compile using emscripten
Use generated JS file in React code
Run the program and smile

helloworld.c

// The famous hello world in C
#include <stdio.h>
#include <string.h>
#include <stdint.h>

int main(){
printf(“Hello World from Cn”);
fflush(stdin);
return 0;
}

Compiling using emcc

emcc helloworld.c -o helloworld.js -s WASM=0 -s ENVIRONMENT=web -s MODULARIZE=1 -s “EXPORT_NAME=’mymodule'”

Files generated by emcc

helloworld.js

Using helloworld.js in React

Copy helloworld.js to a folder in your React src/
eg utils

cp helloworld.js utils/ #Linux command line

React code

import mymodule from ‘../utils/helloworld.js’;

async callCProgram(){
mymodule()
.then(module => {
console.log(‘module loaded!’);
});
}
// Call this function on componentDidMount or on a button click

Run the program

Open the browser & call the url to your React code
Open Developer Tools, console
You will see “Hello World from C” printed in your console
SMILE :), youve called a C program from your React Code

Follow up post on installation coming up soon and may make a series of short posts for emscripten.