11

I have a C program "translated" (dont know what word is appropiate) to Javascript, so I can use it in node.js. C program consists of main that accepts command line parameters. I understand that I need to somehow use module object to pass those command line arguments, but I'm at a loss.

My js program consists of 2 files: program.js (C program compiled into js) and test.js (var module = require('./program.js'), and the rest that operates on this imported program.

The question is: How do I pass some arguments to this C-translated-to-javascript-and-then-imported program?

1

1 Answer 1

14

Emscripten has a global object called Module, which has arguments property. This property contains array of arguments that will get passed in. Just set them before letting emscripten run the compiled program.

Like so, in javascript:

Module['arguments'].push('first_param');
Module['arguments'].push('second_param');

In C:

int main(int argc, char *argv[])
{
    assert(argc == 3);
    assert(strcmp(argv[1], "first_param") == 0);
    assert(strcmp(argv[2], "second_param") == 0);
}

Alternatively you may consider to not build your C code as executable with a main function, but rather as a library that exposes individual C functions to the javascript. Then those functions can have nicely named and typed arguments and you can pass the arguments (almost) directly from javascript when calling them.

3
  • after one pushes the arguments, how do you run the main?
    – eri0o
    Commented Oct 21, 2020 at 23:52
  • If you are building a binary with emscripten, it will call the main for you. To set the arguments before that, it must be done in javascript file given to the --pre-js parameter.
    – michalsrb
    Commented Oct 22, 2020 at 9:49
  • 1
    Thanks! I had to use callMain() and it worked. Also I had to set Module.arguments: [ 'my','arguments'], in the same place all other parameters are set in the HTML so they were set before initializing arguments. BUT IT WORKED! This is super magical.
    – eri0o
    Commented Oct 22, 2020 at 11:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.