Open codeinred opened 1 year ago
Anything can happen in C++, sure. To make all this more manageable, we can use PointerScope: http://bytedeco.org/news/2018/07/17/bytedeco-as-distribution/
If using PointerScope isn't an option, we need to make sure that GetNumbers doesn't get deallocated, yes. Unless something after that references it in Java, it might get deallocated since the JVM cannot know that something else in C++ is still referencing it. To prevent that from deallocating C++ objects though, another way to work around that is to set to the "org.bytedeco.javacpp.nopointergc" system property to "true", if that's OK for your application.
Hi,
Thank you so much for your response! If we enabled nopointergc, would that prevent destructors from being called? This could be problematic for some objects using RAII, and it seems like it would result in most memory being leaked (although please correct me if I'm wrong here)
I will also read into PointerScope.
There is no guarantee that GC ever calls any destructors at all, period. That's not something we can rely on. For C++ libraries that expect RAII, that's what PointerScope is for.
Hello,
We've observed an issue wherein a reference to an internal member variable appears to become dangling after the class that contains that member is garbage-collected.
Question
Can references returned by
@ByRef
-annotated functions become dangling? Is there a way to prevent the reference from becoming dangling, or to instruct javacpp to make a copy of the underlying object?Here, VecVecR and GetNumbers are wrapped types. obj.nums() would return a const reference in C++. The java declaration of
nums()
is annotated with@ByRef
. Full definitions are provided below. On the C++ side of things,GetNumbers
is held by aunique_ptr
toGetNumbersI
.Definitions
Here,
GetNumbers
is a wrapper for a C++ class, where thenums()
function returns a const reference. This reference points to an internal member variable.Is it possible for an instance of
GetNumbers
to be garbage-collected while another variable holds onto the object returned bynums()
?We have a class with a method that returns a vector by const reference:
Source file:
This produces the following class:
Sample code causing crash
Here is roughly the code that causes the issue:
When a line of code that references
obj
is appended to the above, the crash goes away: