简体   繁体   English

如何在Emscripten生成的代码中使用C ++分配的数组?

[英]How to use C++ allocated array in Emscripten generated code?

I have a C++ code like this: 我有这样的C ++代码:

extern "C" {

void MyCoolFunction (int** values)
{
    int howManyValuesNeeded = 5;
    *values = new int[howManyValuesNeeded];
    for (int i = 0; i < howManyValuesNeeded; i++) {
        (*values)[i] = i;
    }
}

}

From C++ it can be used like this: 从C ++可以像这样使用:

int *values = NULL;
MyCoolFunction (&values);
// do something with the values
delete[] values;

Of course the real code is much more complicated, but the point is that the function allocates an int array inside, and it decides what the array size will be. 当然真正的代码要复杂得多,但重点是函数在内部分配一个int数组,并决定数组的大小。

I translated this code with Emscripten, but I don't know how could I access the array allocated inside the function from javascript. 我用Emscripten翻译了这段代码,但我不知道如何从javascript访问函数内部分配的数组。 (I already know how to use exported functions and pointer parameters with Emscripten generated code, but I don't know how to solve this problem.) (我已经知道如何使用导出的函数和指针参数与Emscripten生成的代码,但我不知道如何解决这个问题。)

Any ideas? 有任何想法吗?

In Emscripten, memory is stored as a giant array of integers, and pointers are just indexes into that array. 在Emscripten中,内存存储为一个巨大的整数数组,而指针只是该数组的索引。 Thus, you can pass pointers back and forth between C++ and Javascript just like you do integers. 因此,您可以像在整数中一样在C ++和Javascript之间来回传递指针。 (It sounds like you know how to pass values around, but if not, go here .) (听起来你知道如何传递价值,但如果没有,请到这里 。)

Okay. 好的。 Now if you create a pointer on the C++ side (as in your code above) and pass it over to Javascript, Emscripten comes with a handful of helper functions to allow you to access that memory. 现在,如果您在C ++端创建一个指针(如上面的代码中所示)并将其传递给Javascript,Emscripten会附带一些辅助函数来允许您访问该内存。 Specifically setValue and getValue . 特别是setValuegetValue

Thus, if you passed your values variable into JS and you wanted to access index 5, you would be able to do so with something like: 因此,如果您将值变量传递给JS并且想要访问索引5,则可以使用以下内容执行此操作:

var value5 = getValue(values+(5*4), 'i32');

Where you have to add the index times the number of bytes (5*4) to the pointer, and indicate the type (in this case 32 bit ints) of the array. 您必须将索引的次数添加到指针的字节数(5 * 4),并指示数组的类型(在本例中为32位整数)。

You can call the delete from JavaSCript by wrapping it inside another exported function. 您可以通过将其包装在另一个导出的函数中来调用JavaSCript中的删除。

extern "C" { ...
    void MyCoolFunction (int** values);
    void finsih_with_result(int*);
}

void finsih_with_result(int *values) {
    delete[] values;
}

Alternatively you may also directly do this on JavaScript side: Module._free(Module.HEAPU32[values_offset/4]) (or something like that; code not tested). 或者你也可以在JavaScript方面直接这样做: Module._free(Module.HEAPU32[values_offset/4]) (或类似的东西;未经过测试的代码)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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