IT忍者神龟之使用JNA爬过的坑,JNA路径问题

一号坑: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);
1
这里面的filePath,很多文章里面是直接写文件名,然后把dll文件放到环境变量的目录里面,比如什么C:/windows/system32,还有jdk的bin目录。我只想说,你们烦不烦,做个项目还要到处放文件,误人子弟。就不能放到项目里面带着走?
于是我开始用CLibrary.class.getResource(“”).getPath(),于是几个超级大的坑来了!!!
1、我的文件夹目录中用过空格的,于是得到的地址会带着URI转义过的符号,坑了我很久,所以需要处理下!

CLibrary.class.getResource(“”).getPath().replaceAll(“%20”,” “);
1
2、dll文件绝对不能带下划线“_”,坑爹!!但是文件夹可以带。
3、CLibrary.class.getResource(“”).getPath()的最前面居然会带一条斜杠!?!,也就是得到的路径类似“/D:/project/test”,然后又是找不到路径。这个卡了我又一会。于是最后路径这样了:

String filePath = CLibrary.class.getResource(“”).getPath().replaceFirst(“/”,”“).replaceAll(“%20”,” “)+”sdtapi.dll”;
1
然后文件终于妥妥地放到了我的java文件旁边:
JNA dll文件路径
这样路径不就顺眼多了,比什么放到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]大家一起探讨。

猜你喜欢

转载自blog.csdn.net/vipyhd/article/details/80202658
jna