问题描述
我想了解如何使用 GetDirectBufferAddress
从JNI层。要理解我已经建立一个非常简单的例子:
I am trying to understand how to use GetDirectBufferAddress
from the JNI layer. To understand I've build a very simple example:
public class my_image_info {
static {
System.loadLibrary("my_jni");
}
private java.nio.ByteBuffer image_info_bb;
native static void initc( java.nio.ByteBuffer bb );
my_image_info()
{
image_info_bb = java.nio.ByteBuffer.allocateDirect( 5 * 4 );
initc( image_info_bb );
}
public java.nio.ByteBuffer getBB() {
return image_info_bb;
}
static public void main(String argv[]) {
my_image_info fii = new my_image_info();
java.nio.ByteBuffer bb = fii.getBB();
System.out.println("1: " + bb.getInt(0));
System.out.println("2: " + bb.getInt(4));
System.out.println("3: " + bb.getInt(8));
System.out.println("4: " + bb.getInt(12));
System.out.println("5: " + bb.getInt(16));
}
然后再从本地JNI层:
And then from the native JNI layer:
JNIEXPORT void JNICALL Java_my_1image_1info_initc
(JNIEnv *env, jclass cls, jobject jobj)
{
int *iBuf = (*env)->GetDirectBufferAddress(env, jobj);
iBuf[0] = -2;
iBuf[1] = -1;
iBuf[2] = 0;
iBuf[3] = 1;
iBuf[4] = 2;
}
如果我的OpenJDK运行这个例子在这里(的Debian / Linux的喘息AMD64):
If I run this example over here (debian/linux wheezy amd64) with openjdk :
$ java -version
java version "1.6.0_34"
OpenJDK Runtime Environment (IcedTea6 1.13.6) (6b34-1.13.6-1~deb7u1)
OpenJDK 64-Bit Server VM (build 23.25-b01, mixed mode)
下面是我看到的:
1: -16777217
2: -1
3: 0
4: 16777216
5: 33554432
我理解为指数2和值; 3.但是,所有其他值不作任何意义,我,我本来期望是这样的:
I understand the values for index 2 & 3. But all other values do not make any sense to me, I would have expected something like:
1: -2
2: -1
3: 0
4: 1
5: 2
我是怎么从ByteBuffer的使用在误解JNI?
What did I misunderstood from the ByteBuffer usage in JNI ?
推荐答案
我从文档错过的是,默认情况下 java.nio.ByteBuffer中
实际上是用 BIG_ENDIAN
字节顺序。这也解释了,我看到我的 LITTLE_ENDIAN
系统上的行为。见参考文献(JDK-5043362解释:(BF)NewDirectByteBuffer总是为了ByteOrder.BIG_ENDIAN)
It appears that by default it is always BIG_ENDIAN
, an not effort has been made so far to provide an API for LITTLE_ENDIAN
, as explained in the bug report here (JDK-5043362 : (bf) NewDirectByteBuffer always has order ByteOrder.BIG_ENDIAN).
这篇关于从使用JNI GetDirectBufferAddress的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!