JNI:无法获取数组长度

JNI: Can not get array length

我遇到了下一个问题:我无法用 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;
}

ServerUtil:

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

我的环境:

提前致谢!

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

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

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.

您的本机方法签名不正确。应该是

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