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));
}
}