Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 879
don11995 Avatar asked Feb 08 '23 02:02

don11995


2 Answers

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.

like image 110
Andrew Henle Avatar answered Feb 09 '23 20:02

Andrew Henle


Your native method signature is incorrect. It should be

static jstring convertToHe(JNIEnv *env, jobject thiz, jbytearray array)
like image 24
user207421 Avatar answered Feb 09 '23 20:02

user207421