Saturday, November 9, 2013

Calling C library using JNA ( Direct Mapping )

Here, I am using JNA with Direct Mapping which can improve the performance. A small change is necessary to do this than described in my previous post. This will include only java portion. For other portion, refer to the previous post.

Sample java code: 

File: HelloDirectWorld.java

import com.sun.jna.Library;
import com.sun.jna.Native;

public class HelloDirectWorld {
    public static native void printHello();
    static {
Native.register("useC");
    }

    static public void main(String argv[]) {
        printHello();
    }
}

Command used to compile HelloDirectWorld.java:
javac -classpath .:jna-3.2.3.jar HelloDirectWorld.java 

Command to run our java program:
java -classpath .:jna-3.2.3.jar HelloDirectWorld

The output will be:
Hello Blog World

Enjoy using JNA.

Friday, November 8, 2013

Using JNA(Java Native Access) to use C shared library from java

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();
    }
}

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!!!