Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass string from C++ to JS using emscripten

I am trying to send string from C++ to JS using emscripten but I'm not able to convert it appropriately in JS.

C++

    EMSCRIPTEN_KEEPALIVE const char* accessDetails()
    {
        return func().c_str();
    }

func returns std::string.

I'm getting some garbage value number. How can I get the string in JS?
Thanks in advance.

like image 662
ayush bansal Avatar asked Sep 19 '25 23:09

ayush bansal


1 Answers

When calling a raw WebAssembly function like that you only basic types are supported. In this case you are returned a pointer which is just a number (pointer are number in JS just like they are in C/C++). You can use that pointer to read bytes out of WebAssembly memory and produce a JS string from them using, for example, UTF8ToString(number), or you can use one of the higher level binding systems such as embind to take care of it for you.

See https://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html for more information.

like image 91
sbc100 Avatar answered Sep 22 '25 14:09

sbc100