java使用JNA(Java Native Access)调用dll的方法
jna(java native access):建立在jni之上的java开源框架,sun主导开发,用来调用c、c++代码,尤其是底层库文件(windows中叫dll文件,linux下是so【shared object】文件)。
jni是java调用原生函数的唯一机制,jna就是建立在jni之上,jna简化了java调用原生函数的过程。jna提供了一个动态的c语言编写的转发器(实际上也是一个动态链接库,在linux-i386中文件名是:libjnidispatch.so)可以自动实现java与c之间的数据类型映射。从性能上会比jni技术调用动态链接库要低。
1.简单写个windows下的dll,文件命名为forjava.dll,其中一个add函数,采用stdcall调用约定
main.h文件
#ifndef __main_h__
#define __main_h__
#include <windows.h>
/* to use this exported function of dll, include this header
* in your project.
*/
#ifdef build_dll
#define dll_export __declspec(dllexport) __stdcall
#else
#define dll_export __declspec(dllimport) __stdcall
#endif
#ifdef __cplusplus
extern "c"
{
#endif
int dll_export add(int a,int b);
#ifdef __cplusplus
}
#endif
#endif // __main_h__
main.cpp
#include "main.h"
// a sample exported function
int dll_export add(int a ,int b)
{
return a+b;
}
extern "c" dll_export bool apientry dllmain(hinstance hinstdll, dword fdwreason, lpvoid lpvreserved)
{
switch (fdwreason)
{
case dll_process_attach:
// attach to process
// return false to fail dll load
break;
case dll_process_detach:
// detach from process
break;
case dll_thread_attach:
// attach to thread
break;
case dll_thread_detach:
// detach from thread
break;
}
return true; // succesful
}
2.将jna.jar导入eclipse工程中,java代码如下
//import com.sun.jna.library; cdecl call调用约定
import com.sun.jna.native;
import com.sun.jna.platform;
import com.sun.jna.win32.stdcalllibrary;
public class main {
public interface clibrary extends stdcalllibrary { //cdecl call调用约定时为library
clibrary instance = (clibrary)native.loadlibrary("forjava",clibrary.class);
public int add(int a,int b);
}
public static void main(string[] args) {
system.out.print(clibrary.instance.add(2,3));
}
}