java 調用dll文件時
幾個注意點:
1. package的使用
2. javah的使用
3.path路徑的設定
下面實例介紹java調用dll中的Max函數:
hello.java
package 2hei.net.dll;
public class hello
{
static
{
//System.out.println(System.getProperties().get("java.library.path"));
System.loadLibrary("Hello");
}
public native static int Max(int a,int b);
public static void main(String[] args)
{
int maxnum = 0;
int aa = 10;
int bb = 11;
hello hi= new hello();
maxnum = hi.Max(aa,bb);
System.out.println("max is "+maxnum);
}
}
生成.h頭文件
createh.bat
cd E:/src/java/2hei/net/dll
javah hello
會生成一個2hei_net_dll_hello.h的文件
編輯編輯 2hei_net_dll_hello.h 把#include <jni.h> 改成#include "jni.h"
從jdk的目錄裏面找到jni.h 和 jni_md.h
下面使用VC++生成dll文件。
新建一個dll工程,比如Hello 編輯Hello.cpp
// Hello.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include "Hello.h"
#include "2hei_net_dll_hello.h"
JNIEXPORT jint JNICALL 2hei_net_dll_hello_Max
(JNIEnv *, jclass, jint a, jint b)
{
if(a>=b)return a;
else
return b;
}
編譯工程後,在Debug目錄中找到Hello.dll文件,放到java的path目錄下面。
執行hello.java 即可以得到想要的結果。