I have an existing API library, which is written in C. I'm programming the Java side that should use this API. In order to do so, I want to use JNI. I started to wrap these functions and I have a problem with return types: almost all functions return pointers to the non-simple types, but to very complex types defined in that library. What can I do in such a case?
Created May 4, 2012
Dieter Wimberger I suppose that you are addressing pointers to structures with "very complex types". Well, I can think of two ways:
- Write a wrapper method for each member
of the structure. i.e.:
typedef struct { unsigned short aShort; unsigned char aChar; } ATYPE, *PATYPE; JNIEXPORT jint JNICALL Java_AWrapper_getaShort(JNIEnv *env, jobject obj) { PATYPE inf; inf=nativeFunction(...); return (jint)inf->aShort; } JNIEXPORT jbyte JNICALL Java_AWrapper_getaChar(JNIEnv *env, jobject obj) { PATYPE inf; inf=nativeFunction(...); return (jbyte)inf->aChar; }
Depending on the case, this can be pretty inefficient.
- Pass a specifically designed Java class instance and call upon its set<Attribute> methods to fill in all data that needs to be transferred. Use javap -s <designed class>.java to get the method signatures you need for accessing the Java methods from the native code.
For an example on how to do this see the Java Tutorial, Trail:Java Native Interface, Lesson: Interacting with Java from the Native Side, Calling Java Methods.
This definitely will be more efficient for most cases.