Hello. I tried out the native methods using the following steps:
1. Create the
java file MyFirstNativeImplementation.java:
public class MyFirstNativeImplementation {
static {
System.loadLibrary("NativeTest");
}
public native int getLesserNumber(int x, int y);
public static void main(
String[] args){
MyFirstNativeImplementation myfirstnative = new MyFirstNativeImplementation();
System.out.println(myfirstnative.getLesserNumber(4,5)); // parameters to pass to the native method
}
}
** "NativeTest" is the C++ dll file containing the native method you will create.
2. Compile the java class file: javac MyFirstNativeImplementation.java
3. Create the c++ header file using: javah <class file name> (without the 'class' extension)
** MyFirstNativeImplementation.h is created after executing the command.
4. header file contains the new method signature to use in your c++ program:
JNIEXPORT jint JNICALL Java_MyFirstNativeImplementation_getLesserNumber
(JNIEnv *, jobject, jint, jint);
5. Create your c++ program using the method signature defined in the header file:
a. I wrote the ff. code using Visual Studio .NET. The code is shown below.
Using .NET, I only had to write the last method in the code below.
In your C++ Project, add the existing jni.h file which can be found in your
<JAVA_HOME>\include folder.
You will also need to include directories to your C++ project. In the
.NET menu...Tools..Options...Projects, click on VC++ Directories and
include the following directories:
<JAVA_HOME>\include\win32
<JAVA_HOME>\include
<the directory where MyFirstNativeImplementation.h is located>
Dont forget to include the header file MyFirstNativeImplementation.h
#include "stdafx.h"
#include "NativeTest.h"
#include "MyFirstNativeImplementation.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
BEGIN_MESSAGE_MAP(CNativeTestApp, CWinApp)
END_MESSAGE_MAP()
CNativeTestApp::CNativeTestApp()
{}
CNativeTestApp theApp;
BOOL CNativeTestApp::InitInstance()
{
CWinApp::InitInstance();
return TRUE;
}
JNIEXPORT jint JNICALL Java_MyFirstNativeImplementation_getLesserNumber
(JNIEnv *, jobject, jint x, jint y) {
int result = 0;
if (x < y)
result = x;
if (y < x)
result = y;
return result;
}
b. Build the C++ solution. .NET menu..Build...Build Solution
6. Execute your MyFirstNativeImplementation java file using:
java -Djava.library.path="<directory where your dll is located>" MyFirstNativeImplementation
I'm not really a C++ programmer and I dont know if there is a simplier way. I hope this helps.