Goes through a Java source directory, checks each .java file for native methods and emits C/C++ code accordingly, both .h and .cpp files.
Augmenting Java Files with C/C++
C/C++ code can be directly added to native methods in the Java file as block comments starting at the same line as the method signature. Custom JNI code that is not associated with a native method can be added via a special block comment as shown below. All arguments can be accessed by the name specified in the Java native method signature (unless you use $ in your identifier which is allowed in Java).
package com.badlogic.jnigen; public class MyJniClass { /*JNI #include <math.h> */ public native void addToArray(float[] array, int len, float value); / for(int i = 0; i < len; i++) { array[i] = value; } */ }
The generated header file is automatically included in the .cpp file. Methods and custom JNI code can be mixed throughout the Java file, their order is preserved in the generated .cpp file. Method overloading is supported but not recommended as the overloading detection is very basic. If a native method has strings, one dimensional primitive arrays or direct {@link Buffer} instances as arguments, JNI setup andcleanup code is automatically generated. The following list gives the mapping from Java to C/C++ types for arguments:
Java | C/C++ |
String | char* (UTF-8) |
boolean[] | bool* |
byte[] | char* |
char[] | unsigned short* |
short[] | short* |
int[] | int* |
long[] | long long* |
float[] | float* |
double[] | double* |
Buffer | unsigned char* |
ByteBuffer | char* |
CharBuffer | unsigned short* |
ShortBuffer | short* |
IntBuffer | int* |
LongBuffer | long long* |
FloatBuffer | float* |
DoubleBuffer | double* |
Anything else | jobject/jobjectArray |
If you need control over setting up and cleaning up arrays/strings and direct buffers you can tell the NativeCodeGenerator to omit setup and cleanup code by starting the native code block comment with "/*MANUAL" instead of just "/*" to the method name. See libgdx's Gdx2DPixmap load() method for an example.
.h/.cpp File Generation
The .h files are created via javah, which has to be on your path. The Java classes have to be compiled and accessible to the javah tool. The name of the generated .h/.cpp files is the fully qualified name of the class, e.g. com.badlogic.jnigen.MyJniClass.h/.cpp. The generator takes the following parameters as input:
- Java source directory, containing the .java files, e.g. src/ in an Eclipse project
- Java class directory, containing the compiled .class files, e.g. bin/ in an Eclipse project
- JNI output directory, where the resulting .h and .cpp files will be stored, e.g. jni/
A default invocation of the generator looks like this:
new NativeCodeGenerator().generate("src", "bin", "jni");
To automatically compile and load the native code, see the classes {@link AntScriptGenerator}, {@link BuildExecutor} and{@link JniGenSharedLibraryLoader} classes.
@author mzechner