The JS code can use the JS function writeStringToMemory(string, buffer,
dontAddNull); to convert a JS-side string to a UTF8-encoded C string in
Emscripten HEAP. Then the question is whether the C side or JS side
allocates the memory. If you have a preallocated memory space, you can do
something like

myJSFunctionThatReturnsAString = function(outMemoryArea) {
   var str = "hello";
   writeStringToMemory(str, outMemoryArea);
   // No need to return anything. The string is now written to the memory
area that the user specified.
}

If you want to have the JS side allocate the string, then it would look
something like this:

myJSFunctionThatAllocatesAndReturnsAString = function() {
   var str = "hello";
   var memoryArea = _malloc(str.length+1); // This is correct only if str
is ASCII with no multibyte UTF8 characters! Replace with a UTF8-aware
strlen if needed.
   writeStringToMemory(str, memoryArea);
   return memoryArea; // Return the pointer to newly allocated string to
caller. The caller is responsible for calling free() on the memory, or this
leaks.
}

There's also functions for UTF16 and UTF32 encoded transfer, see the file
tests/utf32.cpp for an example of those.

Jukka


2014-06-03 22:13 GMT+03:00 <[email protected]>:

> What is the best way to return a string from a JS block?  I read the docs
> here but I'm still unclear.  Something like a EM_ASM_STRING.
> https://github.com/kripken/emscripten/wiki/Interacting-with-code
>
> --
> You received this message because you are subscribed to the Google Groups
> "emscripten-discuss" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"emscripten-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to