一个简单的JNA使用例子

1973 查看

使用JAVA语言开发程序比较高效,但有时对于一些性能要求高的系统,核心功能可能是用C或者C++语言编写的,这时需要用到JAVA的跨语言调用功能。JAVA提供了JNI这个技术来实现调用C和C++程序,但JNI实现起来比较麻烦,所以后来SUN公司在JNI的基础上实现了一个框架——JNA
使用这个框架可以减轻程序员的负担,使得JAVA调用C和C++容易很多。以下例子来源于JNA的官方文档,有兴趣研究的同学可以到官网查看更多的例子:

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 standard, stable 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);

        /*
         * 声明一个跟C语言的printf()一样的方法,参数类型要匹配
         * C语言的printf()方法原型如下:
         * int __cdecl printf(const char * __restrict__ _Format,...);
         */
        void printf(String format, Object... args);
    }

    public static void main(String[] args) {
        //调用C语言的printf()方法
        CLibrary.INSTANCE.printf("Hello, World->%d",2014);
    }
}

程序输出结果如下:

Hello, World->2014