|
|
Java Native Interface Programming |
In this section, you will learn how to reference Java programming language types in your native method. You need to reference Java programming language types when you want to:
- Access arguments passed in to a native method from a Java application.
- Create new Java programming language objects in your native method.
- Have your native method return results to the caller.
Java Programming Language Primitive Types
Your native method can directly access Java programming language primitive types such as
booleans,integers,floats, and so on, that are passed from programs written in the Java programming language. For example, the Java typebooleanmaps to the native language typejboolean(represented as unsigned 8 bits), while the Java typefloatmaps to the native language typejfloat(represented by 32 bits). The following table describes the mapping of Java programming language primitive types to native types.Primitive Types and Native Equivalents
Java Type Native Type Size in bits boolean jboolean 8, unsigned byte jbyte 8 char jchar 16, unsigned short jshort 16 int jint 32 long jlong 64 float jfloat 32 double jdouble 64 void void n/a Java Programming Language Object Types
Java programming language objects are passed by reference. All references to Java programming language objects have the type
jobject. For convenience and to avoid programming errors, the JNI implements a set of types that are conceptually all "subtypes" ofjobject, as follows:
jobjectrepresents all Java objects.
jclassrepresents Java class objects (java.lang.Class).jstringrepresents Java strings (java.lang.String).jarrayrepresents Java arrays.
jobjectArrayrepresents arrays of objects.jbooleanArrayrepresents boolean arrays.jbyteArrayrepresents byte arrays.jcharArrayrepresents char arrays.jshortArrayrepresents short arrays.jintArrayrepresents int arrays.jlongArrayrepresents long arrays.jfloatArrayrepresents float arrays.jdoubleArrayrepresents double arrays.jthrowablerepresents Java exceptions (java.lang.Throwable).In our
Prompt.javaexample, the native methodgetLine:takes a Java programming language string as an argument and returns a Java programming language string. Its corresponding native implementation has typeprivate native String getLine(String prompt);jstringfor both the argument and the return value:As mentioned above,JNIEXPORT jstring JNICALL Java_Prompt_getLine(JNIEnv *, jobject, jstring);jstringcorresponds to the Java programming language typeString. Notice that the second argument toJava_Promopt_getLine, which is the reference to the object itself, has typejobject.
|
|
Java Native Interface Programming |