【发布时间】:2026-02-11 13:10:02
【问题描述】:
JNI 教程,例如 this 一,很好地介绍了如何访问对象中的原始字段,以及如何访问作为显式函数参数提供的数组(即作为 jarray 的子类)。但是如何访问位于jobject 中的字段内 的Java(原始)数组?例如,我想对以下 Java 对象的字节数组进行操作:
class JavaClass {
...
int i;
byte[] a;
}
主程序可能是这样的:
class Test {
public static void main(String[] args) {
JavaClass jc = new JavaClass();
jc.a = new byte[100];
...
process(jc);
}
public static native void process(JavaClass jc);
}
相应的 C++ 端将是:
JNIEXPORT void JNICALL Java_Test_process(JNIEnv * env, jclass c, jobject jc) {
jclass jcClass = env->GetObjectClass(jc);
jfieldID iId = env->GetFieldID(jcClass, "i", "I");
// This way we can get and set the "i" field. Let's double it:
jint i = env->GetIntField(jc, iId);
env->SetIntField(jc, iId, i * 2);
// The jfieldID of the "a" field (byte array) can be got like this:
jfieldID aId = env->GetFieldID(jcClass, "a", "[B");
// But how do we operate on the array???
}
我想使用GetByteArrayElements,但它想要一个ArrayType 作为它的参数。显然我错过了一些东西。有没有办法解决这个问题?
【问题讨论】: