简体   繁体   English

emscripten:如何删除C ++代码中分配的std :: vector的内存

[英]emscripten: How to delete memory of std::vector allocated in C++ code

I want to know how to properly delete the memory of std::vector allocated in c++ code and passed to js as function return. 我想知道如何正确删除在c ++代码中分配并作为函数返回传递给js的std :: vector的内存。

My c++ code is 我的C ++代码是

#include <vector>
#include <emscripten/bind.h>

using namespace emscripten;

std::vector<int> intArrayToVector(uintptr_t input, int num){
std::vector<int> vec;
const int* ptr = reinterpret_cast<int*>(input);
for(int i=0; i<num; i++){
    int val = *(ptr+i);
    vec.push_back(val);
}
return vec;
}

EMSCRIPTEN_BINDINGS(test){
register_vector<int>("VectorInt");
function("intArrayToVector", &intArrayToVector, allow_raw_pointer<arg<0>>());  
}

My html code is 我的html代码是

<html>
<body>
 <script src="test.js"></script>
 <script>
   var num = 6;
   var buf = Module._malloc(100);
   var arr = new Int8Array(num);
   for(var i=0; i<num; i++){
      arr[i] = i+2;
   }
Module.HEAP8.set(arr, buf);
var v = Module.intArrayToVector(buf, num);

for(var i=0; i<num; i++){
    console.log(v.get(i));
}
Module._free(buf);

v.resize(0, 0);
v.delete();  
v = {};
</script>
</body>
</html>

I tried the following code to delete the allocated memory but nothing is happening. 我尝试了以下代码来删除分配的内存,但是什么也没有发生。

v.resize(0, 0);
v.delete();  
v = {};

I think v.delete() works. 我认为v.delete()有效。

for (var j = 0;; j++) {
    var v = Module.intArrayToVector(buf, num);

    for(var i=0; i<num; i++){
        console.log(v.get(i));
    }
}

Above infinite loop aborts by Cannot enlarge memory arrays. 无限循环以上将终止, Cannot enlarge memory arrays.

But with v.delete() at end of loop, this program doesn't stop. 但是在循环结束时使用v.delete() ,此程序不会停止。

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

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