是否可以将Java数组传递给采用数组的C/C ++函数? [英] Can a Java array be passed to a C/C++ function which takes an array?

查看:91
本文介绍了是否可以将Java数组传递给采用数组的C/C ++函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在学习有关JNI的知识.让我们说我有一个C/C ++库函数,该函数将int *数组作为输入(我们假设int为4个字节,并像Java中那样进行签名),即,作为指针传递的数组.是否可以通过JNI将int的Java数组传递给此类函数,而无需进行任何复制(显然,这样做时我们删除了Java数组的length部分)?直接ByteBuffer是执行此类操作的唯一可行方法吗?

I am learning about JNI nowadays. Let us say I have a C/C++ library function, which takes int* array as an input (We assume int is of 4 bytes and signed just like as it is in Java), that is, an array passed as a pointer. Would it be possible to pass a Java array of int to such function through JNI, without doing any copying (Obviously we remove the length part of the Java array while doing so)? Is the direct ByteBuffer the only viable method for doing such things?

推荐答案

直接使用ByteBuffer是避免复制的一种方法,就像您提到的那样.

A direct ByteBuffer would be one way of avoiding copying, as you mention yourself.

如果传递Java数组,则需要调用Get<Primitive>ArrayElements,它可能也可能不会复制(或Get<Primitive>ArrayRegion,但这没有意义,因为它总是复制).

If you pass a Java array you will need to call Get<Primitive>ArrayElements, which may or may not copy (or Get<Primitive>ArrayRegion, but that would make no sense since it always copies).

还有GetPrimitiveArrayCritical,如果您只需要在短时间内访问元素,并且在释放元素之前不需要执行任何其他JNI调用,则可以使用GetPrimitiveArrayCritical.比Get<Primitive>ArrayElements更可能"不进行复制.

There's also GetPrimitiveArrayCritical which you can use if you only need access to the elements for a "short" amount of time, and don't need to perform any other JNI calls before releasing the elements. It is "more likely" than Get<Primitive>ArrayElements to not copy.

一个例子:

jint len = env->GetArrayLength(myIntArray);
jint *elements = env->GetPrimitiveArrayCritical(myIntArray, NULL);

// Use elements...

env->ReleasePrimitiveArrayCritical(myIntArray, elements, 0);  

请参见 Oracle的JNI文档.

这篇关于是否可以将Java数组传递给采用数组的C/C ++函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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