BigMac66
BigMac66

Reputation: 914

Using Java to access a third party DLL

I am trying to write a Java program for scientific research equipment that uses National Instruments drivers (DLL) that are written in C. I know nothing about these DLLs at the moment. I can contact NI through my client to get details if required.

My C/C++ skills are ancient so would prefer avoiding anything that requires writing C/C++ code.

Looking for advice that includes pointing me to tutorials. My Java skills are excellent and current it is just my C/C++ that is like a decade old.

Upvotes: 1

Views: 761

Answers (1)

technomage
technomage

Reputation: 10069

The simplest option in your case would likely be JNA.

Here is a simple Hello World example to show you what is involved in mapping the C library's printf function:

package com.sun.jna.examples;

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

/** Simple example of JNA interface mapping and usage. */
public class HelloWorld {

    // This is the simplest way of mapping, which supports extensive
    // customization and mapping of Java to native types.

    public interface CLibrary extends Library {
        CLibrary INSTANCE = (CLibrary)
            Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"),
                               CLibrary.class);

        void printf(String format, Object... args);
    }

    // And this is how you use it
    public static void main(String[] args) {
        CLibrary.INSTANCE.printf("Hello, World\n");
        for (int i=0;i < args.length;i++) {
            CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
        }
    }
}

JNA's JavaDoc and github project include examples and tutorials for a wide range of use cases.

Upvotes: 1

Related Questions