
以下一段代码非常重要就是加载dll:
TestDll1 INSTANCE=(TestDll1) Native.loadLibrary("JNATest",TestDll1.class);
然后声明我们要在java中调用的原生函数:
public void sayUser(UserStruct userStruct);
public void sayCompany(CompanyStruct companyStruct);
然后我们创建一个Test.java,然后在main函数中测试能否调用原生函数。
首先测试sayUser:
UserStruct.ByReference userStruct=new UserStruct.ByReference();
userStruct.id=new NativeLong(100);
userStruct.age=30;
userStruct.name=new WString("SBY");
TestDll1.INSTANCE.sayUser(userStruct);
然后执行。会打印出hello:SBY
再测试sayCompany:
CompanyStruct.ByReference companyStruct=new CompanyStruct.ByReference();
companyStruct.id=new NativeLong(2);
companyStruct.name=new WString("hehe");
companyStruct.count=10;
UserStruct.ByReference pUserStruct=new UserStruct.ByReference();
pUserStruct.id=new NativeLong(90);
pUserStruct.age=99;
pUserStruct.name=new WString("sby");
//pUserStruct.write();
for(int i=0;i<companyStruct.count;i++){
companyStruct.users[i]=pUserStruct;
}
TestDll1.INSTANCE.sayCompany(companyStruct);
会输出一个hello:hehe和10个hello:sby
有些地方会说须要pUserStruct.write()这行代码,目的是把内存固定住,而不被GC释放掉,然而在我测试的时候没有加这一行也能准确执行。预计这个JNA提供的toArray函数有关。
以上就是我的JNA学习心得。之所以会在machine learning的博客中插入这样一篇,基本的目的是大多数的machine leanring的代码都是使用c或者c++编写。而一些场景会须要编写java程序。此时我们须要使用java来调用已经写好的c或者c++函数。
以上源码传送门:?
shareid=2278504517&uk=3977203577
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-81079-3.html
文章中
是事实