java使用JNA(Java Native Access)调用dll的方法
时间:2022-02-06 09:27:34
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));
}
}