2

How can I pass a char* or std::string into an externally defined Javascript function using emscripten?

Currently, when I pass a char* into my externally defined Javascript, a number is printed instead of the string (pointers?).

Here is the code I am using:

mylib.js

mergeInto(LibraryManager.library, {  
    my_js: function(s) {  
        Module.print(s);
        console.log(s);
        document.getElementById('voronoi').innerHTML = s;
    },
 });

main.cpp

int main(int argc, const char * argv[])
{
    char* myString = (char*) malloc(10);
    strncpy(myString, "SOMETHING", 10);
    my_js(myString);
    free(myString);
    return 0;
}

Result printed to the console when running node ./a.out.js:

5260128

Christian Benincasa
  • 1,215
  • 1
  • 21
  • 45

2 Answers2

4

I'm not very familiar with emscripten, but this answer to another question seems to use Pointer_stringify("...") to convert from C strings.

Community
  • 1
  • 1
cobbal
  • 69,903
  • 20
  • 143
  • 156
0

Another way to do this is using embind.

You can refer my answer here for more details.

Community
  • 1
  • 1
Tarun Gehlaut
  • 1,292
  • 10
  • 16