Search code examples
javaandroidcjava-native-interface

JNI: Can not get array length


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!


Solution

  • 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.