Java calls DLL methods using JNA of Java Native Access

  • 2020-04-01 02:27:53
  • OfStack

JNA(Java Native Access) : Java open source framework built on JNI, mainly developed by SUN, used to call C, C++ code, especially the underlying library files (called DLL in Windows, so [Shared object] in Linux).
JNI is the only mechanism for Java to call native functions. JNA is built on top of JNI, and JNA simplifies the process of Java calling native functions. JNA provides a dynamic c-written transponder (actually a dynamic link library, in linux-i386: libjnidispatch. So) that automatically implements the data type mapping between Java and C. This can be lower in performance than JNI technology calls to dynamically linked libraries.
1. Simply write a DLL under Windows, the file named forjava.dll, one of the add functions, using the stdcall calling convention


main.h file 
#ifndef __MAIN_H__ 
#define __MAIN_H__ 

#include <windows.h> 



#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 the eclipse project. The Java code is as follows

//The import com. Sun. Jna. Library; Cdecl call invocation 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 invokes the convention as 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)); 
    } 
}
 


Related articles: