Writing a jni tutorial – sample project

I would not be explaining what jni is and stuff, its available online. I am just writing a small jni sample, so that you easily test it and understand.
First step:
Create a sample java project using netbeans.
This is your sample main file.


public class Test1
{
    static
    {
// this is the name of the dll in c++
        System.load("C:/Documents and Settings/darshan/My Documents/Visual Studio 2008/Projects/testSize/Debug/testDll.dll");
    }
    public static void main(String ar[])
    {
        System.out.println("Hello world from Java");
        String scpp = inDll();
        System.out.println(scpp);
    }
    public native static String inDll();
}

2) Use visual studio to create a DLL project
3) Goto to the command prompt and type:
javah -jni Test1
If this doesnt work, add the javah to the path.
Also Test1 is the name of the class in step1. For better accuracy, try not adding the class in any package although this isnt good, but for testing purposes this is better.
4) You will get an header file generated as below:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class Test1 */
#ifndef _Included_Test1
#define _Included_Test1
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     Test1
 * Method:    inDll
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_Test1_inDll
  (JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif

5) Take this header file and include it in your project in c++
6) Start adding the implemenation in cpp file in c++ as below:

// testDll.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "Test1.h"
#include
using namespace std;
/*
__declspec(dllexport) string returnString()
{
	return "success called";
}
*/
#include
JNIEXPORT jstring JNICALL Java_Test1_inDll
(JNIEnv *env, jobject)
 {
	 return env->NewStringUTF("hi from c++");
}
// below is auto generated class from dll project when done in visual studio
// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}

7) compile the dll and copy it to the place WHERE YOUR CLASS FILES ARE STORED.
sometimes you will get jni.h not found. you need to add the jdk include files in the tools->directories of visual studio for this to work.
8) run the class


java Test1

you will get the output from c++.
good luck!!!!!!

In

,

Leave a Reply

Your email address will not be published. Required fields are marked *