java-jni-01-Introduction
  JKAkDL5PppSO 2023年11月02日 37 0


Introduction


Chapter 1

This chapter introduces the Java Native Interface (JNI). The JNI is a nativeprogramming interface. It allows Java code that runs inside a JavaVirtual Machine (VM) to interoperate with applications andlibraries written in other programming languages, such as C, C++,and assembly.
The most important benefit of the JNI is that itimposes no restrictions on the implementation of the underlyingJava VM. Therefore, Java VM vendors can add support for the JNIwithout affecting other parts of the VM. Programmers can write oneversion of a native application or library and expect it to workwith all Java VMs supporting the JNI.
This chapter covers the following topics:

  • Java Native InterfaceOverview
  • Background
  • Objectives
  • Java Native InterfaceApproach
  • Programming to the JNI
  • Changes

Java Native Interface Overview

While you can write applications entirely in Java,there are situations where Java alone does not meet the needs ofyour application. Programmers use the JNI to write Java native methods to handle those situationswhen an application cannot be written entirely in Java.
The following examples illustrate when you need touse Java native methods:

  • The standard Java class library does not support theplatform-dependent features needed by the application.
  • You already have a library written in another language, andwish to make it accessible to Java code through the JNI.
  • You want to implement a small portion of time-critical code ina lower-level language such as assembly.

By programming through the JNI, you can use nativemethods to:

  • Create, inspect, and update Java objects (including arrays andstrings).
  • Call Java methods.
  • Catch and throw exceptions.
  • Load classes and obtain class information.
  • Perform runtime type checking.

You can also use the JNI with the Invocation API to enable an arbitrary nativeapplication to embed the Java VM. This allows programmers to easilymake their existing applications Java-enabled without having tolink with the VM source code.

Historical Background

VMs from different vendors offer different nativemethod interfaces. These different interfaces force programmers toproduce, maintain, and distribute multiple versions of nativemethod libraries on a given platform.
We briefly examine some of the native methodinterfaces, such as:

  • JDK 1.0 native method interface
  • Netscape’s Java Runtime Interface
  • Microsoft’s Raw Native Interface and Java/COMinterface

JDK 1.0 Native Method Interface

JDK 1.0 was shipped with a native methodinterface. Unfortunately, there were two major reasons that thisinterface was unsuitable for adoption by other Java VMs.

First, the native code accessed fields in Javaobjects as members of C structures. However, the Java Language Specification does not define howobjects are laid out in memory. If a Java VM lays out objectsdifferently in memory, then the programmer would have to recompilethe native method libraries.

Second, JDK 1.0’s native method interfacerelied on a conservative garbage collector. The unrestricted use ofthe unhand macro, for example, made itnecessary to conservatively scan the native stack.

Java Runtime Interface

Netscape had proposed the Java Runtime Interface(JRI), a general interface for services provided in the Javavirtual machine. JRI was designed with portability in mind—itmakes few assumptions about the implementation details in theunderlying Java VM. The JRI addressed a wide range of issues,including native methods, debugging, reflection, embedding(invocation), and so on.

Raw Native Interface and Java/COMInterface

The Microsoft Java VM supports two native methodinterfaces. At the low level, it provides an efficient Raw NativeInterface (RNI). The RNI offers a high degree of source-levelbackward compatibility with the JDK’s native methodinterface, although it has one major difference. Instead of relyingon conservative garbage collection, the native code must use RNIfunctions to interact explicitly with the garbage collector.

At a higher level, Microsoft’s Java/COMinterface offers a language-independent standard binary interfaceto the Java VM. Java code can use a COM object as if it were a Javaobject. A Java class can also be exposed to the rest of the systemas a COM class.

Objectives

We believe that a uniform, well-thought-outstandard interface offers the following benefits for everyone:

  • Each VM vendor can support a larger body of native code.
  • Tool builders will not have to maintain different kinds ofnative method interfaces.
  • Application programmers will be able to write one version oftheir native code and this version will run on different VMs.

The best way to achieve a standard native methodinterface is to involve all parties with an interest in Java VMs.Therefore we organized a series of discussions among the Javalicensees on the design of a uniform native method interface. It isclear from the discussions that the standard native methodinterface must satisfy the following requirements:

  • Binary compatibility - The primary goal is binary compatibilityof native method libraries across all Java VM implementations on agiven platform. Programmers should maintain only one version oftheir native method libraries for a given platform.
  • Efficiency - To support time-critical code, the native methodinterface must impose little overhead. All known techniques toensure VM-independence (and thus binary compatibility) carry acertain amount of overhead. We must somehow strike a compromisebetween efficiency and VM-independence.
  • Functionality - The interface must expose enough Java VMinternals to allow native methods to accomplish useful tasks.

Java Native Interface Approach

We hoped to adopt one of the existing approachesas the standard interface, because this would have imposed theleast burden on programmers who had to learn multiple interfaces indifferent VMs. Unfortunately, no existing solutions are completelysatisfactory in achieving our goals.

Netscape’s JRI is the closest to what weenvision as a portable native method interface, and was used as thestarting point of our design. Readers familiar with the JRI willnotice the similarities in the API naming convention, the use ofmethod and field IDs, the use of local and global references, andso on. Despite our best efforts, however, the JNI is notbinary-compatible with the JRI, although a VM can support both theJRI and the JNI.

Microsoft’s RNI was an improvement over JDK1.0 because it solved the problem of native methods working with anonconservative garbage collector. The RNI, however, was notsuitable as a VM-independent native method interface. Like the JDK,RNI native methods access Java objects as C structures, leading totwo problems:

  • RNI exposed the layout of internal Java objects to nativecode.
  • Direct access of Java objects as C structures makes itimpossible to efficiently incorporate “write barriers,”which are necessary in advanced garbage collection algorithms.

As a binary standard, COM ensures complete binarycompatibility across different VMs. Invoking a COM method requiresonly an indirect call, which carries little overhead. In addition,COM objects are a great improvement over dynamic-link libraries insolving versioning problems.

The use of COM as the standard Java native methodinterface, however, is hampered by a few factors:

  • First, the Java/COM interface lacks certain desired functions,such as accessing private fields and raising generalexceptions.
  • Second, the Java/COM interface automatically provides thestandard IUnknown and IDispatch COM interfaces for Java objects, sothat native code can access public methods and fields.Unfortunately, the IDispatch interface does not deal withoverloaded Java methods and is case-insensitive in matching methodnames. Furthermore, all Java methods exposed through the IDispatchinterface are wrapped to perform dynamic type checking andcoercion. This is because the IDispatch interface is designed withweakly-typed languages (such as Basic) in mind.
  • Third, instead of dealing with individual low-level functions,COM is designed to allow software components (includingfull-fledged applications) to work together. We believe that it isnot appropriate to treat all Java classes or low-level nativemethods as software components.
  • Fourth, the immediate adoption of COM is hampered by the lackof its support on UNIX platforms.

Although Java objects are not exposed to thenative code as COM objects, the JNI interface itself isbinary-compatible with COM. JNI uses the same jump table structureand calling convention that COM does. Thismeans that, as soon as cross-platform support for COM is available,the JNI can become a COM interface to the Java VM.

JNI is not believed to be the only native methodinterface supported by a given Java VM. A standard interfacebenefits programmers, who would like to load their native codelibraries into different Java VMs. In some cases, the programmermay have to use a lower-level, VM-specific interface to achieve topefficiency. In other cases, the programmer might use a higher-levelinterface to build software components. Indeed, as the Javaenvironment and component software technologies become more mature,native methods will gradually lose their significance.

Programming to the JNI

Native method programmers should program to theJNI. Programming to the JNI insulates you from unknowns, such asthe vendor’s VM that the end user might be running. Byconforming to the JNI standard, you will give a native library thebest chance to run in a given Java VM.

If you are implementing a Java VM, you shouldimplement the JNI. JNI has been time tested and ensured to notimpose any overhead or restrictions on your VM implementation,including object representation, garbage collection scheme, and soon. Please send us your feedback if you run into any problems wemay have overlooked.

Changes

As of Java SE 6.0, the deprecated structuresJDK1_1InitArgs and JDK1_1AttachArgs have been removed, insteadJavaVMInitArgs and JavaVMAttachArgs are to be used.


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
JKAkDL5PppSO