emscripten-core / emscripten-core/emscripten

Embind: Memory and reference issues with vectors

Open
#12,455 1 comment 1 reaction 0 assignees View on GitHub
embind
Dominant language
C++
Stars
27.6k
Forks
3.6k
Avg merge
1d 1h
Merged PRs (30d)
105

Description

I have a point class that holds 2d coordinates. I draw coordinate geometry on a canvas in the browser. So i'll need to read the values of the points in a vector on every redraw of the canvas, but I am having two issues. It causes a memory leak, every time I read a point in the vector at same index, i get a different pointer address and it is adding to memory even though i am not creating any memory. Second issue is that I have no way to change the coordinates of the points in the vector.

Emscripten binding code
```
EMSCRIPTEN_BINDINGS(my_module){
emscripten::class_("Point")
.property("x", &Point::x)
.property("y", &Point::y)
.constructor();

emscripten::register_vector("vector_point");
}

```

Creating a vector using js. Point is a class that has double x and double y;
```
var a = new Module.Point(10,10);
var b = new Module.vector_point();
b.push_back(a);

console.log( b.get(0).$$.ptr );
console.log( b.get(0).$$.ptr );
```

Output:
```
9177400
9169656
```

Trying to change the x coordinate of the point at 0th index of the vector
```
b.get(0).x = 100;
console.log(b.get(0).x);
```

Output:
```
10
```

However in C++ this isnt the behaviour. Everything works as expected.
```
vector a;
a.push_back(Point(10,10));

cout << a[0].x << endl;
a[0].x = 100;
cout << a[0].x << endl;

cout << &(a[0]) << endl;
cout << &(a[0]) << endl;
```

Output:
```
10
100
0x7f9ac6c05870
0x7f9ac6c05870
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.