Game Development Reference
In-Depth Information
by the time you read these words, it will likely be more mature. So if you need to debug your
native code, we recommend that you do a quick search for Eclipse NDK plugins and see what's
available.
The NDK doesn't expose most of the Androids APIs, such as the UI toolkit. It is mostly intended
to speed up slow Java methods by rewriting them in C/C++ and calling them from within Java.
Since Android 2.3, Java can be bypassed almost completely by using the NativeActivity class
instead of Java activities. The NativeActivity class is specifically designed to be used for
games with full window control, but it does not give you access to Java at all, so it can't be used
with other Java-based Android libraries. Many game developers coming from iOS choose that
route because it lets them reuse most of the C/C++ on Android without having to go too deep
into the Android Java APIs. However, integration of services such as Facebook authentication or
ads still needs to be done in Java, so designing the game to start in Java and call into C++ via
the JNI is often the most compatible way. With that said, how does one use the JNI?
The Java Native Interface
The Java Native Interface (JNI) is a way to let the virtual machine (and hence Java code)
communicate with C/C++ code. This works in both directions; you can call C/C++ code
from Java, and you can call Java methods from C/C++. Many of Android's libraries use this
mechanism to expose native code, such as OpenGL ES or audio decoders.
Once you use the JNI, your application consists of two parts: Java code and C/C++ code. On
the Java side, you declare class methods to be implemented in native code by adding a special
qualifier called native . This could look like this:
package com.badlogic.androidgames.ndk;
public class MyJniClass {
public native int add( int a, int b);
}
As you can see, the method we declared doesn't have a method body. When the VM running
your Java code sees this qualifier on a method, it knows that the corresponding implementation
is found in a shared library instead of in the JAR file or the APK file.
A shared library is very similar to a Java JAR file. It contains compiled C/C++ code that can be
called by any program that loads this shared library. On Windows, those shared libraries usually
have the suffix .dll ; on Unix systems, they end in .so .
On the C/C++ side, we have a lot of header and source files that define the signature of the
native methods in C and contain the actual implementation. The header file for our class in the
preceding code would look something like this:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_badlogic_androidgames_ndk_MyJniClass */
#ifndef _Included_com_badlogic_androidgames_ndk_MyJniClass
#define _Included_com_badlogic_androidgames_ndk_MyJniClass
#ifdef __cplusplus
extern "C" {
 
Search WWH ::




Custom Search