2

I had compiled a C lib into javascript code by using Emscripten. However I ran into a problem when I try to bind it with my Javascript wrapper.

I wrote this to pass it by reference, I am able to access it via the compiled lib just fine.

var str_to_heapu8 = function (str) {
    return allocate(intArrayFromString(str), 'i8', ALLOC_NORMAL);
}

However, I have trouble retrieving it back to normal javascript string... the return value is an empty string.

var heapu8_to_str = function (ptr, len){
    var array = new Uint8Array(len);
    var i = 0;

    while( (ptr+i) < len){
        array[i] = getValue(ptr+i, 'i8');
        i++;
    }

    return intArrayToString(array);
}

How can I convert it back to javascript string?e

3 Answers 3

1

This works for me:

var heapu8_to_str = function (ptr, len){
    return intArrayToString(HEAPU8.subarray(ptr, ptr+len));
};
Sign up to request clarification or add additional context in comments.

Comments

1

Emscripten (now?) provides a JavaScript function for doing this:

Pointer_stringify(ptr)

Comments

0

The size of the items in the buffer is 8 bytes (because the type is i8), so you need to increment the pointer value in getValue for each entry by 8. You are only increasing by 1. So the correct code would be to change the line in your code to be:

array[i] = getValue(ptr+i*8, 'i8');

1 Comment

An i8 is eight bits (not bytes), which equals one byte. So your increment by eight is incorrect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.