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:
Thanks in advance!
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
.
Your native method signature is incorrect. It should be
static jstring convertToHe(JNIEnv *env, jobject thiz, jbytearray array)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With