Struct operations in Javascript through Emscripten

与世无争的帅哥 提交于 2019-12-01 00:40:44

One way is to use the HEAP* typed arrays exposed by Emscripten, which do have unsigned views:

mergeInto(LibraryManager.library, {
  read_struct: function(myStructPointer, size) {
    // Assumes the struct starts on a 4-byte boundary
    var myNumber = HEAPU32[myStructPointer/4];
    console.log(myNumber);
    // Assumes my_char_array is immediately after my_number with no padding
    var myCharArray = HEAPU8.subarray(myStructPointer+4, myStructPointer+4+32);
    console.log(myCharArray);
  }
});

This works in my test, running Emscripten 1.29.0-64bit, but as noted it makes assumptions about alignment/padding. The cases I tested seemed to show that a struct seemed to always start on a 4 byte boundary, and that 32 bit unsigned integers inside a struct were also always aligned on a 4 byte boundary, and so accessible by HEAPU32.

However, it's beyond my knowledge to know if you can depend on this behaviour in Emscripten. It's my understanding that you can't in usual C/C++ world.

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