Game Development Reference
In-Depth Information
#endif
/*
* Class: com_badlogic_androidgames_ndk_JniUtils
* Method: log
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT
void
JNICALL Java_com_badlogic_androidgames_ndk_JniUtils_log
(JNIEnv *, jclass, jstring, jstring);
/*
* Class: com_badlogic_androidgames_ndk_JniUtils
* Method: copy
* Signature: (Ljava/nio/ByteBuffer;[FII)V
*/
JNIEXPORT
void
JNICALL Java_com_badlogic_androidgames_ndk_JniUtils_copy
(JNIEnv *, jclass, jobject, jfloatArray, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
Time to implement those functions. First, we create a new file called
jniutils.cpp
in the
jni/
folder. Listing 13-3 shows its content.
Listing 13-3. jniutils.cpp, the Implementation of the JniUtils Native Methods
#include
<android/log.h>
#include
<string.h>
#include
"jniutils.h"
We need a few C includes, namely
log.h
, which is provided by the NDK,
string.h
, and our
own
jniutils.h
. The first include lets us use the native Android logging functions. The second
include lets us use
memcpy()
. The last one imports the signatures of our native methods as well
as
jni.h
, which contains the JNI APIs.
JNIEXPORT
void
JNICALL Java_com_badlogic_androidgames_ndk_JniUtils_log
(JNIEnv *env, jclass clazz, jstring tag, jstring message) {
const char
*cTag = env->GetStringUTFChars(tag, 0);
const char
*cMessage = env->GetStringUTFChars(message, 0);
__android_log_print(ANDROID_LOG_VERBOSE, cTag, cMessage);
env->ReleaseStringUTFChars(tag, cTag);
env->ReleaseStringUTFChars(message, cMessage);
}
This function implements the
JniUtils.log()
method, which takes a
JNIEnv
and a
jclass
as
the first two parameters. The
env
parameter allows us to work directly with the JVM. The
jclass
parameter represents the
JniUtils
class. Remember that our methods are static methods.
Instead of getting a
jobject
, as in the previous example, we get the class. The
tag
and
message
parameters are the two strings we pass in from Java.