Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an emscripten compiled C library from node.js

Tags:

node.js

clang

After following instructions on the emscripten wiki I have managed to compile a small C library. This resulted in an a.out.js file.

I was assuming that to use functions from this library (within node.js) something like this would have worked:

var lib = require("./a.out.js");
lib.myFunction('test');

However this fails. Can anyone help or point me to some basic tutorial related to this?

like image 508
lostsource Avatar asked Jan 26 '12 14:01

lostsource


1 Answers

Actually, all the functions are already exported. Generated JavaScript contains following lines:

var ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof require === 'function';
// …

if (ENVIRONMENT_IS_NODE) {
  // …
  module['exports'] = Module;
}

If you got a function called my_fun in your C code, then you'll have Module._my_fun defined.

There are some problems with this approach, though.

Optimizer may remove or rename some functions, so always specify them passing -s EXPORTED_FUNCTIONS="['_main','_fun_one','_fun_two']". Function signatures in C++ are bit mangled, so it's wise to extern "C" { … } the ones which you want to export.

Furthermore, such a direct approach requires JS to C type conversions. You may want to hide it by adding yet another API layer in file added attached with --pre-js option:

var Module = {
  my_fun: function(some_arg) {
    javascript to c conversion goes here;
    Module._my_fun(converted_arg) // or with Module.ccall
  }
}

Module object will be later enhanced by all the Emscripten-generated goodies, so don't worry that it's defined here, not modified.

Finally, you will surely want to consider Embind which is a mechanism for exposing nice JavaScript APIs provided by Emscripten. (Requires disabling newest fastcomp backend.)

like image 175
skalee Avatar answered Sep 28 '22 04:09

skalee