Integrating Java and Native Programs |
In this section, you will learn how to reference Java types in your native method. You need to do this when you want to:
- Access arguments passed in to a native method from a Java application.
- Create Java objects in your native method.
- Have your native method return results to the caller.
Java Primitive Types
Your native method can directly access Java primitive types such as booleans, integers, floats, and so on, that are passed from programs written in Java. For example, the Java type
boolean
maps to the native language typejboolean
(represented as unsigned 8 bits), while the Java typefloat
maps to the native language typejfloat
(represented by 32 bits). The following table describes the mapping of Java 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 Object Types
Java objects are passed by reference. All references to Java objects have the type
jobject
. For convenience and to avoid programming errors, the JNI implements a set of types that are conceptually all subclassed from (or are "subtypes" of)jobject
, as follows:In our
Prompt.java
example, the native methodgetLine
takes a Java string as an argument and returns a Java string:Its corresponding native implementation has typeprivate native String getLine(String prompt);jstring
for both the argument and the return value:JNIEXPORT jstring JNICALL Java_Prompt_getLine(JNIEnv *, jobject, jstring);Graphically, this looks as follows:
As mentioned above,jstring
corresponds to the Java typeString
. Notice that the second argument toJava_Prompt_getLine
, which is the reference to the object itself, has typejobject
.
Integrating Java and Native Programs |