jni和在Java中使用c ++ new'ed对象 [英] jni and using c++ new'ed objects in java

查看:72
本文介绍了jni和在Java中使用c ++ new'ed对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与数据库对话的c ++层,该c ++层执行一个新的SomeObject()并将其返回给Java.

I have a c++ layer that talks to a db, this c++ layer does a new SomeObject() and returns it to java.

什么时候可以通过干净的jni调用删除SomeObject?我可以在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?

推荐答案

正如Daff所写,您不能将C ++对象返回Java",但是您可以做的就是返回对象的地址, :

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 );

您应该确保在根标头中的某个地方,jlong​​的大小足以容纳指针(通常应该这样,因为Java long为64位宽).我使用Boost的静态断言来检查这一点:

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 *));

无论是Java还是C ++,只要需要它(或它的数据),C ++对象就应该一直存在-无论如何,它不能直接被Java删除.当确定可以安全删除它时,可以从java进行另一个JNI调用,传递长值,然后将其强制转换为带有reinterpret_cast<SomeObject *>( the_jlong_value )的适当指针,然后将其删除.当然,您必须手动删除它,JVM完全不知道它的存在,并且所有手动内存管理的警告都适用...

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...

这篇关于jni和在Java中使用c ++ new'ed对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆