Java™ Native Interface (JNI)【读书笔记1】

来源:互联网 发布:寒冷队长知乎 编辑:程序博客网 时间:2024/06/07 03:00

JNI的作用:

• integrating a Java application with legacy code written in languages such as C or C++


• incorporating a Java virtual machine implementation into an existing application written in languages such as C or C++


• implementing a Java virtual machine


• understanding the technical issues in language interoperability, in particular how to handle features such as garbage collection and multithreading


Write a simple Java application that calls a C function. 

The process consists of the following steps:

1. Create a class (HelloWorld.java) that declares the native method.


2. Use javac to compile the HelloWorld source file, resulting in the class file HelloWorld.class. 


3. Use javah -jni to generate a C header file (HelloWorld.h) containing the function prototype for the native method implementation.


4. Write the C implementation (HelloWorld.c) of the native method.


5. Compile the C implementation into a native library, creating HelloWorld.dll or libHelloWorld.so. Use the C compiler and linker available on the host environment.
6. Run the HelloWorld program using the java runtime interpreter. 
Both the class file (HelloWorld.class) and the native library (HelloWorld.dll or libHelloWorld.so) are loaded at runtime.

下图讲得很明白:

1、先创建Java层面的本地方法,AAA.java。这里面定义了许多function。

2、通过javac来compile出AAA.class,这个class有两个作用,runtime时候用到、经一步生成对应的C层面的AAA.h

3、通过javah -jni和编译好的AAA.class来生成AAA.h(具体的操作方面请看下一章:Java JNI之javec javah的用法)

4、编写AAA.c这个本地方法的C实现。

5、编译AAA.c,生成一个本地库。如libAAA.so

6、运行AAA.Java。这个AAA.class和本地so库都是在runtime的时候被加载。



0 0
原创粉丝点击