Friday, August 3, 2012

Invoking native C/C++ lib from Java and JNA

So as a continuation of the last post http://orphanware.blogspot.com/2012/08/making-c-available-through-native-calls.html......here is how u connect using JNA:
  1. compile your native lib to so or dll and place it in your LIB_LIBRARY_PATH on linux or in your PATH in windows (IMPORTANT needs to start with "lib". So if it's mylib it should be libmylib
  2. download jna.jar and platform.jar either manually or with a tool like maven
  3. create an interface that extends com.sun.jna.Native
  4. create class to use (not implement) the interface
here is sampe interface


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


interface MyLib extends Library {

        MyLib INSTANCE = (MyLib) Native.loadLibrary("mylib", MyLib.class );
        String MYLIB_helloWorld();
        
}

and a class that uses it


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

public class MyLibUser{


        public static void main( String[] args ) {

                MyLib lib = MyLib.INSTANCE;

                lib.MYLIB_helloWorld();
        }


}

now compile with
javac -cp jna.jar:. -Djna.nosys=true  MyLibUser
and run with
java -cp jna.jar:. -Djna.nosys=true  MyLibUser
Gaaaangsta! No?

No comments:

Post a Comment