I have a c++ layer that talks to a db, this c++ layer does a new SomeObject() and returns it to java.
When is it safe for me to say delete SomeObject via my clean jni call. Can I delete as soon as java has the returned object or do I need to copy the object and then delete?
解决方案
As Daff wrote, you can't “return a C++ object to Java,” but what you can do is return the address of the object, as a long:
jlong obj_ptr = reinterpret_cast( &obj );
You should make sure somewhere in a root header that the size of jlong is enough to hold pointers (it generally should be, as a Java long is 64-bit wide). I use Boost's static assert to check this:
#include
BOOST_STATIC_ASSERT(sizeof(jlong)>=sizeof(void *));
The C++ object should live as long as it (or its data) is needed, be it in Java or C++ — anyway, it can't be deleted by Java directly. When you determine that you can safely delete it, you can make another JNI call from java, passing the long value, cast it to the appropriate pointer with a reinterpret_cast( the_jlong_value ), and delete it. Of course, you have to delete it manually, the JVM is totally unaware of its existence, and all caveats of manual memory management apply...