java c new,jni和在Java中使用c ++ new'ed对象

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值