c++11 - C++ shared_ptr and Java native Object ownership -
c++11 - C++ shared_ptr and Java native Object ownership -
while exposing functionalities c++ library java faced problem regarding c++ shared_ptr
pointers. case object jlong
handle related object lives whithin java portion subsequent structures access object using smart pointers.
the problem got is: when smart pointer gets destroyed or reset underlying object gets deleted well. java reference points still object.
i tried lot did not manage maintain ownership on java-side. there best practices or solutions problem ?
if want hold object long java keeps reference it, here useful pattern:
jlong java_xxx_getnativeref(...) { std::shared_ptr<myobject> *pnew = new std::shared_ptr<myobject>; *pnew = whatever-you-do obtain std::shared_ptr<myobject>; homecoming reinterpret_cast<jlong>(pnew); } java_xxx_releasenativeref(..., jlong nativeref) { std::shared_ptr<myobject> *psp = reinterpret_cast<std::shared_ptr<myobject> *>(nativeref); psp->clear(); }
on other hand, if concerned java reference may become invalid because outlives lifecycle of native object, don't want java command release of myobject, can same trick std::weak_ptr
.
java c++11 jni shared-ptr
Comments
Post a Comment