i have been working on example of jni.......on ubuntu 10.04
after making c file according to jni interface .h file, i compiled it to get .so file(static library)...but unable to run the native code....here is the piece of work what i done...............
1) ReadFile.java
import java.util.*;
class ReadFile {
//Native method declaration
native byte[] loadFile(String name);
//Load the library
static {
System.loadLibrary("nativelib");
}
public static void main(String args[]) {
byte buf[];
//Create class instance
ReadFile mappedFile=new ReadFile();
//Call native method to load ReadFile.java
buf=mappedFile.loadFile("ReadFile.java");
//Print contents of ReadFile.java
for(int i=0;i<buf.length;i++) {
System.out.print((char)buf[i]);
}
}
}
2) compile java file
3) javah -jni ReadFile
and i get ReadFile.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class ReadFile */
#ifndef _Included_ReadFile
#define _Included_ReadFile
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: ReadFile
* Method: loadFile
* Signature: (Ljava/lang/String
[B
*/
JNIEXPORT jbyteArray JNICALL Java_ReadFile_loadFile
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
4) and made a c file with nativelib.c and interfaces defined in .h
#include <jni.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
JNIEXPORT jbyteArray JNICALL Java_ReadFile_loadFile
(JNIEnv * env, jobject jobj, jstring name) {
caddr_t m;
jbyteArray jb;
jboolean iscopy;
struct stat finfo;
const char *mfile = (*env)->GetStringUTFChars(
env, name, &iscopy);
int fd = open(mfile, O_RDONLY);
if (fd == -1) {
printf("Could not open %s\n", mfile);
}
lstat(mfile, &finfo);
m = mmap((caddr_t) 0, finfo.st_size,
PROT_READ, MAP_PRIVATE, fd, 0);
if (m == (caddr_t)-1) {
printf("Could not mmap %s\n", mfile);
return(0);
}
jb=(*env)->NewByteArray(env, finfo.st_size);
(*env)->SetByteArrayRegion(env, jb, 0,
finfo.st_size, (jbyte *)m);
close(fd);
(*env)->ReleaseStringUTFChars(env, name, mfile);
printf("hurray........done...\n");
return (jb);
}
5) then i execute this command to generate staticlibrary
gcc -I/usr/lib/jni -I/usr/lib/jvm/java-1.6.0-openjdk -
I/usr/lib/jvm/java-1.6.0-openjdk/include -shared -o libnativelib.so nativelib.c
please check whether this is correct or not....it generates static library with name libnativelib.so
6) then i set paths with commands
LD_LIBRARY_PATH=`pwd`
export LD_LIBRARY_PATH
7) at the end when i run the java class with command
java ReadFile it gives following error
Exception in thread "main" java.lang.UnsatisfiedLinkError: no nativelib in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1681)
at java.lang.Runtime.loadLibrary0(Runtime.java:840)
at java.lang.System.loadLibrary(System.java:1047)
at ReadFile.<clinit>(ReadFile.java:8)
Could not find the main class: ReadFile. Program will exit.
please tell me where i lack
thank you in advance