The JavaTM Native Interface (JNI) is a powerful feature of the Java platform. Applications that use the JNI can incorporate native code written in programming languages such as C and C++, as well as code written in the Java programming language. The JNI allows programmers to take advantage of the power of the Java platform, without having to abandon their investments in legacy code. Because the JNI is a part of the Java platform, programmers can address interoperability issues once, and expect their solution to work with all implementations of the Java platform.
This book is both a programming guide and a reference manual for the JNI. The book consists of three parts:
本书各部分概述
- Chapter 2 introduces the JNI through a simple example. It is a tutorial intended for the beginning users who are unfamiliar with the JNI.
通过例子介绍JNI,适合入门 - Chapters 3 to 10 constitute a programmer's guide that gives a broad overview of a number of JNI features. We will go though a series of short but descriptive examples to highlight various JNI features and to present the techniques that have proven to be useful in JNI programming.
- Chapters 11 to 13 present the definitive specification for all JNI types and functions. These chapters are also organized to serve as a reference manual.
The book assumes that you have basic knowledge of the Java, C, and C++ programming languages. If not, you may refer to one of the many excellent books that are available: The JavaTM Programming Language, Second Edition, by Ken Arnold and James Gosling (Addison-Wesley, 1998), The C Programming Language, Second Edition, by Brian Kernighan and Dennis Ritchie (Prentice Hall, 1988), and The C++ Programming Language, Third Edition, by Bjarne Stroustrup (Addison-Wesley, 1997).
阅读本书的前提
The remainder of this chapter introduces the background, role, and evolution of the JNI.
1.1 The Java Platform and Host Environment
Because this book covers applications written in the Java programming language as well as in native (C, C++, etc.) programming languages, let us first clarify the exact scope of the programming environments for these languages.
The Java platform is a programming environment consisting of the Java virtual machine (VM) and the Java Application Programming Interface (API).1 Java applications are written in the Java programming language, and compiled into a machine-independent binary class format. A class can be executed on any Java virtual machine implementation. The Java API consists of a set of predefined classes. Any implementation of the Java platform is guaranteed to support the Java programming language, virtual machine, and API.
Java platform是一个由Java虚拟机和Java API组成的开发环境。Java程序由Java语言编写,被编译成机器无关代码,可以在Java虚拟机上执行。Java API由一些预定义的类组成,任何Java的platform的实现保证支持Java语言、虚拟机和API.
The term host environment represents the host operating system, a set of native libraries, and the CPU instruction set. Native applications are written in native programming languages such as C and C++, compiled into host-specific binary code, and linked with native libraries. Native applications and native libraries are typically dependent on a particular host environment. A C application built for one operating system, for example, typically does not work on other operating systems.
术语“host环境”代表host操作系统,一系列native libraries和CPU指令集。Native程序由C或C++编写,编译成为host专有二进制代码,与native库链接。Native应用程序和native库依赖特定的host环境。比如,一个在某个操作系统上编译的C程序不能在另一个OS上运行。
Java platforms are commonly deployed on top of a host environment. For example, the Java Runtime Environment (JRE) is a Sun product that supports the Java platform on existing operating systems such as Solaris and Windows. The Java platform offers a set of features that applications can rely on independent of the underlying host environment.
Java platform通常部署在host 环境的最上层。比如,JRE是Sun的产品,支持Solaries和Windows上的Java platform。Java platform提供了一系列独立于host环境的功能
1.2 Role of the JNI
When the Java platform is deployed on top of host environments, it may become desirable or necessary to allow Java applications to work closely with native code written in other languages. Programmers have begun to adopt the Java platform to build applications that were traditionally written in C and C++. Because of the existing investment in legacy code, however, Java applications will coexist with C and C++ code for many years to come.
The JNI is a powerful feature that allows you to take advantage of the Java platform, but still utilize code written in other languages. As a part of the Java virtual machine implementation, the JNI is a two-way interface that allows Java applications to invoke native code and vice versa. Figure 1.1 illustrates the role of the JNI.
作为Java虚拟机的一部分,JNI是一个two-way接口,允许Java程序触发native code以及相反
![](https://i-blog.csdnimg.cn/blog_migrate/f3ffb4cf118c1994627f0d26fb806247.png)
The JNI is designed to handle situations where you need to combine Java applications with native code. As a two-way interface, the JNI can support two types of native code: native libraries and native applications.
JNI可以支持两种类型的native code:native库和native程序
- You can use the JNI to write native methods that allow Java applications to call functions implemented in native libraries. Java applications call native methods in the same way that they call methods implemented in the Java programming language. Behind the scenes, however, native methods are implemented in another language and reside in native libraries.
可以用Java程序调用native写的方法 - The JNI supports an invocation interface that allows you to embed a Java virtual machine implementation into native applications. Native applications can link with a native library that implements the Java virtual machine, and then use the invocation interface to execute software components written in the Java programming language. For example, a web browser written in C can execute downloaded applets in an embedded Java virtual machine implemention.
可以在native程序中嵌入一个Java虚拟机的实现。Native程序可以链接实现Java虚拟机的native库,。。。比如,一个用C写的浏览器可以在嵌入的Java虚拟机实现中执行downloaed applet。(不解)
Remember that once an application uses the JNI, it risks losing two benefits of the Java platform.
一旦使用了JNI,可能面临失去Java platform优势
First, Java applications that depend on the JNI can no longer readily run on multiple host environments. Even though the part of an application written in the Java programming language is portable to multiple host environments, it will be necessary to recompile the part of the application written in native programming languages.
首先,使用了JNI的Java程序不能在多个host环境上执行。
Second, while the Java programming language is type-safe and secure, native languages such as C or C++ are not. As a result, you must use extra care when writing applications using the JNI. A misbehaving native method can corrupt the entire application. For this reason Java applications are subject to security checks before invoking JNI features.
其次,安全问题
As a general rule, you should architect the application so that native methods are defined in as few classes as possible. This entails a cleaner isolation between native code and the rest of the application.
作为惯例,应该把native方法局限在尽可能少的几个类里,与程序其他部分隔绝
1.4 When to Use the JNI
Before you embark on a project using the JNI, it is worth taking a step back to investigate whether there are alternative solutions that are more appropriate. As mentioned in the last section, applications that use the JNI have inherent disadvantages when compared with applications written strictly in the Java programming language. For example, you lose the type-safety guarantee of the Java programming language.
A number of alternative approaches also allow Java applications to interoperate with code written in other languages. For example:
有很多Java程序与其他语言程序通信的替代方案
- A Java application may communicate with a native application through a TCP/IP connection or through other inter-process communication (IPC) mechanisms.
IPC - A Java application may connect to a legacy database through the JDBCTM API.
- A Java application may take advantage of distributed object technologies such as the Java IDL API.
Sometimes, however, you may find it necessary for a Java application to communicate with native code that resides in the same process. This is when the JNI becomes useful. Consider, for example, the following scenarios:
以下情况建议使用JNI
- The Java API might not support certain host-dependent features needed by an application. An application may want to perform, for example, special file operations that are not supported by the Java API, yet it is both cumbersome and inefficient to manipulate files through another process.
Java不支持的操作 - You may want to access an existing native library and are not willing to pay for the overhead of copying and transmitting data across different processes. Loading the native library in the same process is much more efficient.
使用已有的native库 - Having an application span multiple processes could result in unacceptable memory footprint. This is typically true if these processes need to reside on the same client machine. Loading a native library into the existing process hosting the application requires less system resources than starting a new process and loading the library into that process.
- You may want to implement a small portion of time-critical code in a lower-level language, such as assembly. If a 3D-intensive application spends most of its time in graphics rendering, you may find it necessary to write the core portion of a graphics library in assembly code to achieve maximum performance.
改进关键部分的性能
总之,最好在同一个进程
1.5 Evolution of the JNI
The need for Java applications to interoperate with native code has been recognized since the very early days of the Java platform. The first release of the Java platform, Java Development Kit (JDKTM) release 1.0, included a native method interface that allowed Java applications to call functions written in other languages such as C and C++. Many third-party applications, as well as the implementation of the Java class libraries (including, for example, java.lang, java.io, and java.net), relied on the native method interface to access the features in the underlying host environment.
Unfortunately, the native method interface in JDK release 1.0 had two major problems:
JDK1中的两个主要问题
- First, the native code accesses fields in objects as members of C structures. However, the Java virtual machine specification does not define how objects are laid out in memory. If a given Java virtual machine implementation lays out objects in a way other than that assumed by the native method interface, then you have to recompile the native method libraries.
- Second, the native method interface in JDK release 1.0 relies on a conservative garbage collector because native methods can get hold of direct pointers to objects in the virtual machine. Any virtual machine implementation that uses more advanced garbage collection algorithms cannot support the native method interface in JDK release 1.0.
- Each virtual machine implementor can support a larger body of native code.
- Development tool vendors do not have to deal with different kinds of native method interfaces.
- Most importantly, application programmers are able to write one version of their native code and this version will run on different implementations of the Java virtual machine.
The JNI is the native interface supported by all Java virtual machine implementations. From JDK release 1.1 on, you should program to the JNI. The old-style native method interface is still supported in Java 2 SDK release 1.2, but will not (and cannot) be supported in advanced Java virtual machine implementations in the future.
Java 2 SDK release 1.2 contains a number of JNI enhancements. The enhancements are backward compatible. All future evolutions of JNI will maintain complete binary compatibility.
1.6 Example Programs
This book contains numerous example programs that demonstrate JNI features. The example programs typically consist of multiple code segments written in the Java programming language as well as C or C++ native code. Sometimes the native code refers to host-specific features in Solaris and Win32. We also show how to build JNI programs using the command line tools (such as javah) shipped with JDK and Java 2 SDK releases.
Keep in mind that the use of the JNI is not limited to specific host environments or specific application development tools. The book focuses on writing the code, not on the tools used to build and run the code. The command line tools bundled with JDK and Java 2 SDK releases are rather primitive. Third-party tools may offer an improved way to build applications that use the JNI. We encourage you to consult the JNI-related documentation bundled with the development tools of your choice.
本书只关注写代码
You can download the source code of the examples in this book, as well as the latest updates to this book, from the following web address: http://java.sun.com/docs/books/jni/