Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jni and using c++ new'ed objects in java

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?

like image 842
arinte Avatar asked Jan 22 '23 21:01

arinte


1 Answers

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<jlong>( &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.hpp>
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<SomeObject *>( 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...

like image 170
Jean-Philippe Pellet Avatar answered Mar 01 '23 23:03

Jean-Philippe Pellet