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?
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>
A few thoughts:
crwap
or
ccall
?var length = Module.ccall('stringLen', ['string'], 'number');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With