我是抱着吐槽的態度來發這篇博客的,真坑!百度找了好久,好不容易纔一點一點摸索實驗出來,就是一個爬坑之旅。
一號坑:32位JDK
這個屬於我小白了,具體報了
Native library (win32-x86/sdtapi.dll) not found
之類的錯誤。
後來換了一個eclipse自帶的32位報
Unsupported major.minor version 51.0
,原來用了jdk1.6。沒辦法,重新下載換過來。你妹的JNA只能用32位,我16G內存多少年沒用過32位JDK了。
二號坑:路徑問題
(CLibrary) Native.loadLibrary(filePath, CLibrary.class);
這裏面的filePath,很多文章裏面是直接寫文件名,然後把dll文件放到環境變量的目錄裏面,比如什麼C:/windows/system32,還有jdk的bin目錄。我只想說,你們煩不煩,做個項目還要到處放文件,誤人子弟。就不能放到項目裏面帶着走?
於是我開始用CLibrary.class.getResource(“”).getPath(),於是幾個超級大的坑來了!!!
1、我的文件夾目錄中用過空格的,於是得到的地址會帶着URI轉義過的符號,坑了我很久,所以需要處理下!
CLibrary.class.getResource("").getPath().replaceAll("%20"," ");
2、dll文件絕對不能帶下劃線“_”,坑爹!!但是文件夾可以帶。
3、CLibrary.class.getResource(“”).getPath()的最前面居然會帶一條斜槓!?!,也就是得到的路徑類似“/D:/project/test”,然後又是找不到路徑。這個卡了我又一會。於是最後路徑這樣了:
String filePath = CLibrary.class.getResource("").getPath().replaceFirst("/","").replaceAll("%20"," ")+"sdtapi.dll";
然後文件終於妥妥地放到了我的java文件旁邊:
這樣路徑不就順眼多了,比什麼放到D盤目錄,放到環境變量目錄舒服多了。
好的,最後附上完整版demo代碼:
package com.modules.ksdll.test;
import java.net.URL;
import com.sun.jna.*;
public class Test {
public static void main(String[] args) {
try {
//調用方法
int result = CLibrary.sdtapi.InitComm(1001);
System.out.println("result:"+result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
interface CLibrary extends Library {
//絕對路徑的地址獲取,注意要去空格,特別坑
String filePath = CLibrary.class.getResource("").getPath().replaceFirst("/","").replaceAll("%20"," ")+"sdtapi.dll";
CLibrary sdtapi = (CLibrary) Native.loadLibrary(filePath, CLibrary.class);
//動態鏈接庫中的方法
int InitComm(int port);
//動態鏈接庫中的方法
int Authenticate();
//==============================================dll public method e
}
注意這裏面的InitComm都是dll文件裏面的方法,如果不知道dll內容的,下載一個DEPENDS.EXE進行查看。
感謝大家,最後,如果大家有什麼問題,請發送郵件到[email protected]大家一起探討。