ayush bansal
ayush bansal

Reputation: 43

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.

Upvotes: 3

Views: 2983

Answers (1)

sbc100
sbc100

Reputation: 3022

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.

Upvotes: 4

Related Questions