JNI: Can not get array length

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

I faced with the next problem: I can not do anything with byte[] (jbyteArray) in C code. All functions that work with array in JNI cause JNI DETECTED ERROR IN APPLICATION: jarray argument has non-array type. What's wrong with my code?

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; } 

ServerUtil:

public class ServerUtil {      public ServerUtil() {         System.loadLibrary("shadow");     }      public native String convertToHex(byte[] array); } 

Main 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);     } } 

My environment:

  • Android Studio 2.0
  • Experimental Gradle plugin 0.7.0
  • JAVA 1.8
  • NDK r11b
  • Windows 10 x64

Thanks in advance!

回答1:

The second argument passed to your function isn't a jbyteArray.

Per the JNI documentation, the arguments passed to a native function are:

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.

Your jstring convertToHex(JNIEnv* env, jbyteArray array) is missing the second jclass or jobject argument, so you're treating either a jobject or jclass argument and a jbyteArray.



回答2:

Your native method signature is incorrect. It should be

static jstring convertToHe(JNIEnv *env, jobject thiz, jbytearray array) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!