有什么方法可以通过 JNI 获取指向 Java 数组的直接指针吗?
我需要通过 JNI 获取包含 Java 数组的直接内存地址的指针,而不调用某种复制(即直接访问)。
GetArrayElements 返回一个指向复制数组的指针 - 我需要能够直接从本机层修改 Java 层上的 int[] 。
从 jintArray
转换为 int*
成功返回内存地址,但我不确定这是否特别稳定......?
我在这里能做些什么吗...?
I need to get a pointer containing the direct memory address of a Java array, via JNI, without invoking some sort of copying (ie direct access).
GetArrayElements returns a pointer to a copied array - I need to be able to modify an int[] on the Java layer directly from a the native layer.
Casting from a jintArray
to an int*
returns the memory address successfully, but I'm not sure if this is particularly stable...?
Is there anything I can do here...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用直接内存(具有本机字节顺序)的 IntBuffer。在 JNI 中,您可以使用地址作为指针。在 Java 中,您必须使用 get() 和 put()。
You can use an IntBuffer using direct memory (with native byte order). In JNI you can use the address as a pointer. In Java you have to use the get() and put().
或许。您可以调用一些方法,这些方法可能会为您提供指向 Java 内存的直接指针,但这取决于 JVM 的功能。
来自 http://java.sun.com/docs/books/ jni/html/objtypes.html#4099 :
请注意,完成操作后需要释放指针。
编辑:
在 JDK 1.3 中,函数 Get/ReleasePrimtiveArrayCritical() 来获取直接指针,即使 JVM 不支持固定。
但是,您应该尽快释放该指针,并且与 JVM 的交互受到限制。
如果您与大型数组进行频繁但稀疏的交互,另一种方法是仅获取数组中的小区域,使用 GetArrayRegion() 函数。
Maybe. There are methods you can call that might give you a direct pointer to the Java memory, but that depends on the capabilities of the JVM.
From http://java.sun.com/docs/books/jni/html/objtypes.html#4099 :
Note that you need to release the pointer when you're through with it.
EDIT:
In JDK 1.3, the functions Get/ReleasePrimtiveArrayCritical() were added to obtain a direct pointer even if the JVM does not support pinning.
However, you're expected to release the pointer as soon as possible, and there are restrictions on your interactions with the JVM.
An alternative, if you have frequent but sparse interactions with a large array, is to get only small regions in the array, with GetArrayRegion() functions.
另一种方法是获取其地址并使用 GetDirectBufferAddress 方法设置一个指向它的指针。您可以在下面的链接中找到更多信息:
GetDirectBufferAddress 示例对于复杂的对象
Another way is getting its address and set one pointer to it with GetDirectBufferAddress method. You can find more information below link:
GetDirectBufferAddress example for a complex object