Java 调用Native Method 和Library

来源:互联网 发布:公租房信息管理 源码 编辑:程序博客网 时间:2024/06/08 19:11

Java 调用Native Method和Libary,就会丢失Java自己的一些属性,比如夸平台运行,除非你确认必须调用Native Method 和Library,否则尽量别用,我们通常这样用的原因是之前我们写了很多代码,希望重用,或者是因为执行速度的原因我们需要利用Native code去运行特定的功能。

1. 调用Native Method和Library的例子,

public class SimpleFile {public static final char separatorChar='>';protected String path;protected int fd;public SimpleFile(String path) {// TODO Auto-generated constructor stubthis.path = path;}public String getFileName(){int index = path.lastIndexOf(separatorChar);return index <0? path: path.substring(index +1);}public String getPath(){return this.path;}public native boolean open();public native void close();public native int read(byte[] buffer, int length);public native int write(byte[] buffer, int length);// run when the class is loaded first time.static {System.loadLibrary("Simple"); //simple.dll}}
然后正常调用SimpleFile中的open等方法,

SimpleFile sf = new SimpleFile(">some>path>and>filename");sf.open();byte[] buffer = new byte[1024];sf.read(buffer, buffer.length);fillBufferWithData(buffer, buffer.length);sf.write(buffer, buffer.length);sf.close();

2. 写C代码,

根据我们的定义,我们需要在DLL(Simple.dll)中实现如上native 函数(open, close, read 等等),那么首先我们需要通过这个SimpleFile类去产生对应的头文件,

2.1 利用Javah.exe去产生头文件,

为了生成对应的头文件,我们需要先编译源文件,比如本例中的SimpleFile.java,编译为SimpleFile.class, 然后利用javah + 类名(加上package名字)的形式产生对应的头文件,

例如本例 javah MySubPackage/SimpleFile,则在目录下会产生MySubPackage_SimpleFile.h,里面会有如下具体的定义。

/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class MySubPackage_SimpleFile */#ifndef _Included_MySubPackage_SimpleFile#define _Included_MySubPackage_SimpleFile#ifdef __cplusplusextern "C" {#endif#undef MySubPackage_SimpleFile_separatorChar#define MySubPackage_SimpleFile_separatorChar 62L/* * Class:     MySubPackage_SimpleFile * Method:    open * Signature: ()Z */JNIEXPORT jboolean JNICALL Java_MySubPackage_SimpleFile_open  (JNIEnv *, jobject);/* * Class:     MySubPackage_SimpleFile * Method:    close * Signature: ()V */JNIEXPORT void JNICALL Java_MySubPackage_SimpleFile_close  (JNIEnv *, jobject);/* * Class:     MySubPackage_SimpleFile * Method:    read * Signature: ([BI)I */JNIEXPORT jint JNICALL Java_MySubPackage_SimpleFile_read  (JNIEnv *, jobject, jbyteArray, jint);/* * Class:     MySubPackage_SimpleFile * Method:    write * Signature: ([BI)I */JNIEXPORT jint JNICALL Java_MySubPackage_SimpleFile_write  (JNIEnv *, jobject, jbyteArray, jint);#ifdef __cplusplus}#endif#endif


通过分析上面头文件的名字,就会发现命名格式Java_Package名字_类名_函数名。


2.2 编写C代码,

要按照头文件中的函数声明去编写实现C代码,

3,编译Java代码

在实现C代码之后,编译C代码,产生dll(windows 下),将dll 放入对应的目录下, Java程序在运行过程中去加载该dll(具体加载dll的方式有好几种,将在后面学习).

原创粉丝点击