about 10 years ago
Hello Guy's
This Blog will guide how to create DLL file from java using JNI.
Please follow the below instructions.
First create a java file that contains the native method and it loads the DLL file.
Create TestDLL.java and put below code :
- public class TestDLL
- {
- private native String getMsg(); // native method
- static
- {
- System.loadLibrary(TestDLL); // load dll file
- }
- public static void main(String ars[])
- {
- System.out.println(new TestDLL.getMsg()); // Access the method of dll file
- }
- }
public class TestDLL { private native String getMsg(); // native method static { System.loadLibrary(TestDLL); // load dll file } public static void main(String ars[]) { System.out.println(new TestDLL.getMsg()); // Access the method of dll file } }
Compile java file:
Create an c header file using javah as follows:
That c header file looks like
- /* DO NOT EDIT THIS FILE it is machine generated */
- #include <jni.h>
- /* Header for class TestDLL */
- #ifndef _Included_TestDLL
- #define _Included_TestDLL
- #ifdef __cplusplus
- extern C {
- #endif
- /*
- *Class: TestDLL
- *Method: getMsg
- *Signature: ()Ljava/lang/String;
- */
- JNIEXPORT jstring JNICALL Java_TestDLL_getMsg
- (JNIEnv *,jobject);
- #ifdef cplusplus
- }
- #endif
- #endif
/* DO NOT EDIT THIS FILE it is machine generated */ #include <jni.h> /* Header for class TestDLL */ #ifndef _Included_TestDLL #define _Included_TestDLL #ifdef __cplusplus extern C { #endif /* *Class: TestDLL *Method: getMsg *Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_TestDLL_getMsg (JNIEnv *,jobject); #ifdef cplusplus } #endif #endif
After that create a c++ file that defines the native method which is declared in
java file, and after creating c header file it will show in that header file as
follows :
Note: for creating c++ file Dev C++ tool is best for me and for you also.
The c++ file is :
- #include<jni.h>
- #include<stdio.h>
- #include<string.h>
- #include TestDLL.h
- JNIEXPORT jstring JNICALL Java_TestDLL_getMsg
- (JNIEnv *env,jobject obj)
- {
- return env->NewStringUTF(Welcome to findnerd.com);
- }
#include<jni.h> #include<stdio.h> #include<string.h> #include TestDLL.h JNIEXPORT jstring JNICALL Java_TestDLL_getMsg (JNIEnv *env,jobject obj) { return env->NewStringUTF(Welcome to findnerd.com); }
After creating c++ file create a project in dev c++ :
1. New Project ->DLL
2. Enter project Name TestDLL and checked on C++ Project.
3. Click on OK Button.
After that close the default open files without saving them.
Add C header file and C++ file to the project.
Right click on project and go to project option
1. Project Option -> Directories -> Include Directories
2. Add both java directories path
i.e
3. Click on OK button.
Go to Execute menu and click on Rebuild All or press Ctrl+F11
It creates the dll file after that when we run the code via below command, we got output .
OutPut :
0 Comment(s)