How do I access the Emscripten typed array from javascript?

孤街醉人 提交于 2019-12-11 03:32:23

问题


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


回答1:


This works for me:

var heapu8_to_str = function (ptr, len){
    return intArrayToString(HEAPU8.subarray(ptr, ptr+len));
};



回答2:


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');



回答3:


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

Pointer_stringify(ptr)


来源:https://stackoverflow.com/questions/16586273/how-do-i-access-the-emscripten-typed-array-from-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!