Tuesday, June 26, 2007

Java Native Method Calling - Tute 1


Using java native method

I will do this with simple program Hello.java

1. javac Hello.java
2. javah –jni Hello
It will create a “Hello.h” header file for the native method we are using.
Do not edit that
3. write the your native file “Hello.c”
including “Hello.h” and jni.h and other header files as needed
4. next step compile the Hello.c
take visual studio command prompt
cl -I ”C:\Program Files\Java\jdk1.5.0_11\include”
-I ”C:\Program Files\Java\jdk1.5.0_11\include\win32”
-LD Hello.c -Felibnative.dll

This will create libnative.lib, libnative.exp, Hello.obj, libantive.dll
* you should give the path to libnative.dll in the “Hello.java”

5. to run the java file
java Hello ------- will give "Hello world!" as output

Codes

1.Hello.java

class Hello{
public native void sayHello();
static{
System.load("C:\\java\\test\\Hello\\New Folder\\libnative.dll");
}
public static void main(String[] args){
Hello h = new Hello();
h.sayHello();
}
}

2. Hello.h – this is created header file in the second step

/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class Hello */

#ifndef _Included_Hello
#define _Included_Hello
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Hello
* Method: sayHello
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_Hello_sayHello
(JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

3. Hello.c

#include
#include "Hello.h"
#include

JNIEXPORT void JNICALL Java_Hello_sayHello
(JNIEnv *env, jobject obj)
{
printf("Hello world!\n");
return;
}

No comments: