How to pass strings between C++ and javascript via emscripten

tenfour picture tenfour · Feb 16, 2014 · Viewed 9.1k times · Source

I am learning emscripten, and I can't even get the most basic string manipulation working, when passing strings between C++ and JS.

For example, I would like to write a string length function. In C++:

extern "C" int stringLen(std::string p)
{
    return p.length();
}

Called from javascript as:

var len = _stringLen("hi.");

This yields 0 for me. How do I make this work as expected? Which string type should I use here? char const*? std::wstring? std::string? None seem to work; I always get pretty random values.

This is only the beginning... How do I then return a string from C++ like this?

extern "C" char *stringTest()
{
    return "...";
}

And in JS:

var str = _stringTest();

Again, I cannot find a way to make this work; I always get garbage in JS.

So my question is clearly: How do I marshal string types between JS and C++ via Emscripten?

Answer

FacePalm picture FacePalm · Aug 26, 2014

extern "C" doesn't recognize std::string.

You may want to try this:
Test.cpp

#include <emscripten.h>
#include <string.h>

extern "C" int stringLen(char* p)
        {
            return strlen(p);
        }

Use the following command to compile the cpp code :

emcc Test.cpp -s EXPORTED_FUNCTIONS="['_stringLen']

Sample test code :
Test.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Hello World !</title>
        <script src="a.out.js"></script>
        <script>
             var strLenFunction =  Module.cwrap('stringLen', 'number', ['string']);
             var len1 = strLenFunction("hi.");  // alerts 3
             alert(len1);
             var len2 = strLenFunction("Hello World"); // alerts 11
             alert(len2);
        </script>
    </head>
</html>