Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 747
tenfour Avatar asked Feb 16 '14 21:02

tenfour


2 Answers

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>
like image 67
FacePalm Avatar answered Sep 18 '22 01:09

FacePalm


A few thoughts:

  1. The only way I have called a method is by using crwap or ccall?
    var length = Module.ccall('stringLen', ['string'], 'number');
  2. Are you including stringLen and stringTest in your EXPORTED_FUNCTIONS parameter?
    emcc hello_world.cpp ... -s EXPORTED_FUNCTIONS=['_stringLen','_stringTest']

Take a look here for more details:
http://kripken.github.io/emscripten-site/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html

Or my hello_world tutorial:
http://www.brightdigit.com/hello-emscripten/

Hopefully that helps.

like image 45
leogdion Avatar answered Sep 19 '22 01:09

leogdion