Game Development Reference
In-Depth Information
#endif
/*
* Class: com_badlogic_androidgames_ndk_MyJniClass
* Method: add
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_com_badlogic_androidgames_ndk_MyJniClass_add
(JNIEnv *, jobject, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
This header file was generated with a JDK tool called javah . The tool takes a Java class as input,
and generates a C function signature for any native methods it finds. There's a lot going on here,
as the C code needs to follow a specific naming schema and needs to be able to marshal Java
types to their corresponding C types (e.g., Java's int becomes a jint in C). We also get two
additional parameters of type JNIEnv and jobject . The first can be thought of as a handle to
the VM. It contains methods to communicate with the VM, such as to call methods of a class
instance. The second parameter is a handle to the class instance on which this method was
invoked. We could use this in combination with the JNIEnv parameter to call other methods of
this class instance from the C code.
This header file does not contain the implementation of the function yet. We need a
corresponding C/C++ source file that implements the function:
#include "myjniclass.h"
JNIEXPORT jint JNICALL Java_com_badlogic_androidgames_ndk_MyJniClass_add
(JNIEnv * env, jobject obj, jint a, jint b) {
return a + b;
}
These C/C++ sources are compiled to a shared library, which we then load through a specific
Java API so that the VM can find the implementation of the native methods of our Java classes:
System.loadLibrary("myjnitest");
int result = new MyJniClass().add(12, 32);
The call to System.loadLibrary() takes the name of the shared library. How it finds the
corresponding file is up to the VM implementation to some degree. This method is called only
once, at startup, so that the VM knows where to find the implementations of any native libraries.
As you can see, we can invoke the MyJniClass.add() method just like any other Java class
method!
Enough of all this talk. Let's get our hands dirty with a little C code on Android! We will write a
few simple C functions that we want to invoke from our Java application. We'll guide you through
the process of compiling the shared library, loading it, and calling into the native methods.
Search WWH ::




Custom Search