Listing 114 jnicookbookc

return factorial(n-1)*n;

jint Java_com_cookbook_advance_ndk_ndk_factorial( JNIEnv* env, jobject thiz, jint n ) {

return factorial(n);

Inside this C program, there is a special type jint, which is the Java type defined in C/C+ + .This provides a way to pass native types to Java. If return values from Java to C are necessary, a casting can be done. Table 11.1 summarizes the type mapping between Java and native description.

Table 11.1 Type Mapping Between Java and Native

Java Type in C/C++

Native Type



unsigned char

unsigned 8 bits


signed char

signed 8 bits


unsigned short

unsigned 16 bits



signed 16 bits



signed 32 bits



32 bits


long long int64

signed 64 bits



64 bits

There are two functions inside the C program.The first factorial function is used to do actual calculations. Java calls the second function.The name of the function should always be defined as the JAVA_CLASSNAME_METHOD format for interface.

There are three parameters in the second function: a JNIEnv pointer, a jobject pointer, and a Java argument the Java method declares. JNIEnv is a Java Native Interface (JNI) pointer passed as an argument for each native function. These functions are mapped to a Java method that is the structure that contains the interface to the Java Virtual Machine (JVM). It includes the functions necessary to interact with the JVM and to work with Java objects. In this example, it does not use any Java functions.The only argument needed for this program is the Java argument jint n.

The makefile for the builder is shown in Listing 11.5. It should be placed at the same location as the C program. It contains a definition of the local_path for the builder and a call to CLEAR_VARS to clean up all local_* variables before each build. Then, the local_module is identified as the name of the custom library ndkcookbook and identifies the source code files to build.After all these declarations, it includes the BUILD_SHARED_LIBRARY.This is a generic makefile for building a simple program. More detailed information on the makefile format is provided in the ANDROID-MK.TXT file under the docs/ directory of the NDK.

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook

Post a comment