DEV Community

amythical
amythical

Posted on

Call C binary from javascript WITHOUT process.exec

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 C\n");
  fflush(stdin);
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Compiling using emcc

emcc helloworld.c -o helloworld.js -s WASM=0 -s ENVIRONMENT=web  -s MODULARIZE=1 -s "EXPORT_NAME='mymodule'"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)