I am writing simple example of JNA which will use C program to print "Hello Blog World". I am using Ubuntu 13.04 64 bit system for this.
Sample code of C :
File: useC.c
#include <stdio.h>
void printHello(){
printf("Hello Blog World\n");
}
Command use to create shared library:
I am using 64 bit system so I have to add -fpic options.
gcc -c -fpic useC.c
This will create useC.o file which is compiled object file.
gcc -shared -o libuseC.so useC.o
This will create useC.so file which is shared library. This file is used from our Java code.
Sample code of java:
File: HelloWorld.java
import com.sun.jna.Library;
import com.sun.jna.Native;
public class HelloWorld {
public interface UsingCFromJava extends Library {
public void printHello();
}
static public void main(String argv[]) {
UsingCFromJava uc = (UsingCFromJava) Native.loadLibrary("useC", UsingCFromJava.class);
uc.printHello();
}
}
Command used to compile HelloWorld.java:
javac -classpath .:jna-3.2.3.jar HelloWorld.java
This will create two files: HelloWorld.class and HelloWorld$UsingCFromJava.class.
Now, we have to export the location of our shared library into export LD_LIBRARY_PATH.
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
At the end of this, the folder contains these files:
HelloWorld.class, HelloWorld.java, HelloWorld$UsingCFromJava.class, jna-3.2.3.jar, libuseC.so, useC.c, useC.o, useC.so
Sample code of C :
File: useC.c
#include <stdio.h>
void printHello(){
printf("Hello Blog World\n");
}
Command use to create shared library:
I am using 64 bit system so I have to add -fpic options.
gcc -c -fpic useC.c
This will create useC.o file which is compiled object file.
gcc -shared -o libuseC.so useC.o
This will create useC.so file which is shared library. This file is used from our Java code.
Sample code of java:
File: HelloWorld.java
import com.sun.jna.Library;
import com.sun.jna.Native;
public class HelloWorld {
public interface UsingCFromJava extends Library {
public void printHello();
}
static public void main(String argv[]) {
UsingCFromJava uc = (UsingCFromJava) Native.loadLibrary("useC", UsingCFromJava.class);
uc.printHello();
}
}
Now, you have to download jna jar file. I have download it from maven repository. I have used jna-3.2.3.jar. I have kept it on the same folder where there is HelloWorld.java.
Command used to compile HelloWorld.java:
javac -classpath .:jna-3.2.3.jar HelloWorld.java
This will create two files: HelloWorld.class and HelloWorld$UsingCFromJava.class.
Now, we have to export the location of our shared library into export LD_LIBRARY_PATH.
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
Now to run our java program,
java -classpath .:jna-3.2.3.jar HelloWorld
The output will be:
Hello Blog World
At the end of this, the folder contains these files:
HelloWorld.class, HelloWorld.java, HelloWorld$UsingCFromJava.class, jna-3.2.3.jar, libuseC.so, useC.c, useC.o, useC.so
Enjoy JNA!!!
No comments:
Post a Comment