JNA (Java Native Access): Java Open source framework built on JNI, sun-led development, used to invoke C, C + + code, especially the underlying library files (called DLL files in Windows, Linux is so "shared object" file).
JNI is the only mechanism for Java to invoke native functions, JNA is based on JNI, JNA simplifies the process of Java calling native functions. JNA provides a dynamic C-language-written forwarder (in fact, also a dynamic-link library, in linux-i386 the filename is: libjnidispatch.so) can automatically implement the data type mapping between Java and C. Performance will be lower than the JNI technology call dynamic link library.
1. Simple to write a DLL under Windows, file named Forjava.dll, one of the add function, using the stdcall calling convention
Copy Code code as follows:
Main.h file
#ifndef __main_h__
#define __main_h__
#include <windows.h>
/* To use this exported function of the 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. Import Jna.jar into Eclipse project, Java code is as follows
Copy Code code as follows:
Import Com.sun.jna.Library; CDECL Call calling convention
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 calling convention time for 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));
}
}