Previous | Next | Trail Map | Java Native Interface | Contents

Interacting with Java from the Native Side

The JNI offers a set of standard interface functions. Using these interface functions, you can call JNI functions from your native method code to do such things as access and manipulate Java objects, release Java objects, create new objects, call Java methods, and so on.

This section shows you how to use JNI functions from a native method. Each example consists of a program written in Java that calls various native methods implemented in the C programming language. The native methods, in turn, may call JNI functions to access the Java objects.

Accessing Java Strings

Strings are a particularly useful kind of object. The JNI provides a set of string manipulation functions to ease the task of handling Java strings in native code. Using these functions, the programmer can translate between Java strings and native strings in Unicode and UTF-8 formats.

Accessing Java Arrays

Arrays are another kind of frequently-used Java object. You can use JNI array manipulation functions to create arrays and access array elements.

Calling Java Methods

The JNI supports a complete set of "callback" operations that allow you to invoke a Java method from the native code. You locate the method using its name and signature. You can also invoke both class and instance methods. Use the javap tool to generate JNI-style method signatures from class files.

Accessing Java Member Variables

The JNI allows you to locate a Java member variable using the member variable's name and type signature. You can locate and access both class and instance member variables. The javap tool helps you to generate JNI-style member variable signatures from class files.

Catching and Throwing Exceptions

This section teaches you how to deal with exceptions from within a native method implementation. Your native method can catch, throw, and clear exceptions.

Local and Global References

Native code can refer to Java objects using either local or global references. Local references are only valid within a native method invocation. Local references are freed automatically after the native method returns. Global references remain valid throughout an application. You must explicitly allocate and free global references.

Threads and Native Methods

This section describes the implications of running native methods in the multi-threaded Java platform. The JNI offers basic synchronization constructs for native methods.

JNI Programming in C++

In C++, the JNI presents a slightly cleaner interface and performs additional static type checking.


Previous | Next | Trail Map | Java Native Interface | Contents