简体   繁体   中英

How to return an array of unknown size in Enscripten?

I have a C/C++ function that returns two arrays each the size that is unknown before the call. I need to call this function from JavaScript. (For simplicity, one array is returned in the example).

extern "C" {
  void produce_object_3d(float* verts, int *num_verts);
}

Note that JavaScript does not know std::vector and boost:array and other types. I currently pre-allocate some space, but it will not work. Here is the code on the JavaScript side:

var verts_address = Module._malloc(FLOAT_SIZE*3*max_verts);
var nv_address = Module._malloc(INT_SIZE*1);
//
produce_object_3d (verts_address, nv_address);
//
var nverts = Module.HEAPU32[nv_address/INT_SIZE];
var verts = Module.HEAPF32.subarray(verts_address/FLOAT_SIZE, verts_address/FLOAT_SIZE + 3*nverts);

This is not efficient. Also what if the size of the result is large and there is not enough memory pre-allocated?

For your particular case using embind is a better option. As per the official documentation

For convenience, embind provides factory functions to register std::vector (register_vector()) and std::map (register_map()) types:

 EMSCRIPTEN_BINDINGS(stl_wrappers) { register_vector<int>("VectorInt"); register_map<int,int>("MapIntInt"); } 

The returned object has methods like .get() and .size()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM