Wednesday, March 3, 2010

Wrapping native libraries with JNA: Dingo

Even with the advent of pure Java chemoinformatics toolkits like MX or the CDK, there is a lot of interesting native code floating around on the net. Unfortunately, wrapping native code with JNI is no real fun.

JNA comes to the rescue. It does all the neccessary loading and marshalling stuff dynamically in the background for you. All you need is a declaration of the native interface, the rest is magic.

Here's an incomplete but working example for Dingo 1.0:

package your_package_here;
import com.sun.jna.Native;
public class NativeDingoWrapper {

  static {
    Native.register("dingo");
  }

  public static native int dingoSetOutputFormat(String anOutputFormat);
  public static native int dingoSetColoring(int aColoringFlag);
  public static native int dingoSetHighlightColorEnabled(int aHighlightFlag);
  public static native int dingoSetHighlightThicknessEnabled(int aHighlightThicknessFlag);
  public static native int dingoSetStereoOldStyle(int aStereoFlag);
  public static native int dingoSetImageSize(int aWidth, int aHeight);
  public static native int dingoLoadMolFromString(String aMol);
  public static native int dingoLoadMolFromFile(String aFile);
  public static native int dingoSetOutputFile(String anOutputFile);
  public static native int dingoRender();
  public static native int dingoMoleculeIsEmpty();
}


And that's it.

The only drawback of JNA is that it needs a glue DLL specific to the operating system, so theoretically it is more platform limited than JNI.

But since "JNA has been built and tested on OSX (ppc, x86, x86_64), linux (x86, amd64), FreeBSD/OpenBSD (x86, amd64), Solaris (x86, amd64, sparc, sparcv9) and Windows (x86, amd64). It has also been built for windows/mobile and Linux/ppc64, although those platforms are not included in the distribution." this is a quite limited limitation for most cases.

I have successfully wrapped Dingo and Barsoi with JNA and up to now it just works as advertised.

1 comment:

  1. Hello Ernst-Georg,

    Thank you for playing with Dingo C interface and JNA. Glad it worked.

    As you already know, new release of Dingo (version 1.2) contains JNI wrapper for Windows (x64/x64), Linux (x64/x64), and Mac OS X (x86/x64/ppc).

    The existence of JNA is a pleasant surprise to me. We will consider using the JNA in Dingo wrapper in future releases, although we may decide to keep it on JNI, because of issues JNA may have with loading the appropriate binary for current platform and throwing exceptions from C to Java. Thank you for information anyway.


    With best regards,

    Dmitry

    ReplyDelete