Reputation: 6297
I have an existing C code already, that I use in other projects. I investigated a way to reuse the C code in my Android app and came accross the NDK and got everything worked out.
But in order to make it work, I had to create that JNI file that basically wraps my C code.
For example,
here is my C code :
multiply.h
int mult(int val1, int val2);
multiple.c
int mult(int val1, int val2) { return val1 * val2; }
Then I had to create the multiply-jni file that looks like this :
multiply-jni.c
#include <jni.h>
#include "multiply.h"
jint Java_com_example_ndktest_NativeLib_mult
(JNIEnv * env, jobject obj, jint value1, jint value2)
{
return mult(value1, value2);
}
And then I use the ndk-build tool to generate the shared library.
My question is, is there a way to generate the multiply-jni.c file automatically? I really don't want to do this by hand, as the C code can be very large ...
Upvotes: 2
Views: 1207
Reputation: 20812
You could try to parse the .h file and emit a .java file. With JNI, you get to design a Java class with methods that are natural in Java and then implement them in C. It is often helpful to do some of the implementation in Java so your class might have a public interface and private native method declarations. Once you compile your .java file to a .class file you can use javah
to generate a .h file for your JNI implementations.
If you'd rather do all of the work in Java, you can use JNA. It uses Java classes to call into the JNA library (which itself uses JNI). JNAerator can convert .h files into the required Java code. To use JNAerator effectively, you might want to rewrite your .h file to just include the types and functions that you want to use in Java.
Update: Somewhat similar to JNAerator is SWIG. "SWIG is typically used to parse C/C++ interfaces and generate the 'glue code' required for the ... target languages to call into ... C/C++ code."
Again simplifying the header file is advantageous. SWIG also allows you to annotate the C declarations to guide it's code generation. It too uses JNI underneath.
Upvotes: 3