Java is a very powerful program. It can do a lot of operations. Next I will introduce the program code for calling windows dll files in java. For your reference, please refer.
JNA (Java Native Access): An open-source Java framework built on JNI. SUN leads the development and is used to call C and C ++ code, especially the underlying library files (dll files in windows and so [shared object] files in linux ).
JNI is the only mechanism for Java to call native functions. JNA is built on JNI. JNA simplifies Java's process of calling native functions. JNA provides a dynamic C language editor (actually a dynamic link library, in the Linux-i386 file name is: libjnidispatch. so) can automatically realize the data type ing between Java and C. The performance is lower than that of the dynamic link library called by JNI technology.
1. Write a windows dll and name the file forjava. dll. One of the add functions adopts the stdcall call convention.
| The Code is as follows: |
Copy code |
|
Main. h file
# 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. Import jna. jar into the eclipse project. The java code is as follows:
| The Code is as follows: |
Copy code |
|
// 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 {// Library when cdecl call is called
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 ));
}
} |