gpt4 book ai didi

java - JNI : Can not get array length

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:02:27 25 4
gpt4 key购买 nike

我遇到了下一个问题:我不能用 C 代码中的 byte[] (jbyteArray) 做任何事情。在 JNI 中使用数组的所有函数都会导致 JNI DETECTED ERROR IN APPLICATION: jarray argument has non-array type。我的代码有什么问题?

C:

#include <stdio.h>
#include <jni.h>

static jstring convertToHex(JNIEnv* env, jbyteArray array) {
int len = (*env)->GetArrayLength(env, array);// cause an error;
return NULL;
}

static JNINativeMethod methods[] = {
{"convertToHex", "([B)Ljava/lang/String;", (void*) convertToHex },
};

JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved)
{
JNIEnv* env = NULL;

if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_4) != JNI_OK) {
return -1;
}

jclass cls = (*env)->FindClass(env, "com/infomir/stalkertv/server/ServerUtil");

(*env)->RegisterNatives(env, cls, methods, sizeof(methods)/sizeof(methods[0]) );

return JNI_VERSION_1_4;
}

服务器工具:

public class ServerUtil {

public ServerUtil() {
System.loadLibrary("shadow");
}

public native String convertToHex(byte[] array);
}

主要 Activity :

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ServerUtil serverUtil = new ServerUtil();
byte[] a = new byte[]{1,2,3,4,5};
String s = serverUtil.convertToHex(a);
}
}

我的环境:

  • Android Studio 2.0
  • 实验性 Gradle 插件 0.7.0
  • Java 1.8
  • NDK r11b
  • Windows 10 x64

提前致谢!

最佳答案

传递给函数的第二个参数不是 jbyteArray

根据 JNI documentation ,传递给 native 函数的参数是:

Native Method Arguments

The JNI interface pointer is the first argument to native methods. The JNI interface pointer is of type JNIEnv. The second argument differs depending on whether the native method is static or nonstatic. The second argument to a nonstatic native method is a reference to the object. The second argument to a static native method is a reference to its Java class.

The remaining arguments correspond to regular Java method arguments. The native method call passes its result back to the calling routine via the return value.

您的 jstring convertToHex(JNIEnv* env, jbyteArray array) 缺少第二个 jclassjobject 参数,因此您正在处理一个 jobjectjclass 参数和一个 jbyteArray

关于java - JNI : Can not get array length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37082509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com