Java的JNI - 关联使用C与Java对象分配的资源? [英] Java JNI - associating resources allocated in C with java objects?

查看:239
本文介绍了Java的JNI - 关联使用C与Java对象分配的资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C分配一些内存,并保持与Java对象实例相关联的,是这样的:

I want to allocate some memory in C and keep it associated with a java object instance, like this:

void configure(JNIEnv *object, jobject obj, ....) {
  char *buf = new char[1024];
  // associated <buf> with <obj> somehow
}

再后来释放内存当Java对象获取垃圾回收 - 通过调用从JNI的功能,我能做到这一点在完成()的java对象的方法

问题是,我该如何与Java对象C指针相关联?保持一个字段中的对象,并转换指针到吗?有没有更好的办法?

The question is, how do I associate a C pointer with the java object? Keep a long field in the object and cast the pointer to long? Is there a better way?

推荐答案

一般来说,如果你想要一个指针从C到Java转移,建议使用等等有足够的比特来保存所述指针值的情况下,该平台是64位。

Generally, if you want to transfer a pointer from C to Java, it's recommended to use long so that there are enough bits to hold the pointer value in case the platform is 64 bits.

然后,看看<一个href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/nio/ByteBuffer.html#allocateDirect%28int%29\"><$c$c>ByteBuffer.allocateDirect()它创建一个的ByteBuffer 实例,内存可以与C共享您可以分配这种直接的ByteBuffer 从Java端然后将它作为 jobject 来一个JNI函数,这里面JNI函数您使用<$c$c>GetDirectBufferAddress功能。

Then, have a look at ByteBuffer.allocateDirect() which creates a ByteBuffer instance which memory can be shared with C. You can allocate such a direct ByteBuffer from the Java side then pass it as a jobject to a JNI function and inside this JNI function you use the GetDirectBufferAddress function.

另一种方法是包裹的与<存储器的本地区href=\"http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-14.html#NewDirectByteBuffer\"><$c$c>NewDirectByteBuffer JNI从本机端的功能。它给你一个 jobject 您传递回Java端(注意局部和全局引用)。要注意一个事实,即一旦直接的ByteBuffer 封装了本机内存已经创建,你仍然负责管理本机内存:在某些时候,你将不得不叫删除BUF; 您的母语code,Java将不会为你做

Another way is to wrap a native area of memory with the NewDirectByteBuffer JNI function from the native side. It gives you a jobject you pass back to the Java side (pay attention to local and global references). Pay attention to the fact that once the direct ByteBuffer that wraps the native memory has been created, you are still responsible for managing the native memory: at some point, you will have to call delete buf; in your native code, Java won't do it for you.

这篇关于Java的JNI - 关联使用C与Java对象分配的资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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