一个简单的JNA使用例子

发布时间:2019-08-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了一个简单的JNA使用例子脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

使用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

脚本宝典总结

以上是脚本宝典为你收集整理的一个简单的JNA使用例子全部内容,希望文章能够帮你解决一个简单的JNA使用例子所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。