I get this problem when I wanna call a native C function in java on android use JNI. I pass a pointer to structure as a parameter in that C function, and allocate memory to that pointer.
So please tell me how can I call this C function in java? I googled for a long time but get no rewards.
Codes like this, A is the name of structure :
JNIEXPORT int JNICALL
Java_pkgname_NativeTools_create(JNIEnv *env, jclass jclazz, A **ptr) {
*ptr = (A*) malloc(sizeof(A));
if (*ptr != NULL ) {
return 0;
} else {
return -1;
}
}
and I don’t know how to write the native interface :
public class NativeTools{
static {
System.loadLibrary("LibName");
}
// TODO don't know what type in JNI should I use to declare this native function?
public static native int create(?);
}
thanks a lot and sorry for my poor english 🙁
You can’t do it like this. You can use only JNI datatypes as C function parameters. Anyway, there is nothing like structs or even pointers in Java. What was it, that you wanted to create on Java side and then “pass it to C” ? The nearest to pointer you could get is a reference type
jobject, but C doesn’t understand it as simply as you tried. It’s a reference to JVM object, not C struct. It’s only meant as a parameter to further JNI calls (which calls back to JVM).There are tools which could help you improving the datatype interoperability (SWIG,JNA), but given the apparent fundamental misunderstanding, you should start with some basic reading:
(can’t do a proper link, SO forbids IP addresses)