Java中使用JNA调用其他语言编写的动态链接库

来源:互联网 发布:过河进销存软件 编辑:程序博客网 时间:2024/06/15 06:01

在开发中有时需要跨平台跨语言,用Java调用其它语言编写的动态链接库,例如编译好的dll文件,这是就需要用到JNA(Java Native Access ),JNA是建立在经典的JNI的基础之上的一个跨平台框架,下面简单介绍一下在Java中如何使用JNA调用其他语言编写dll动态链接库文件。大致可以分为一下几步:
1、下载jna.jar包,并导入到Java项目中;
下载地址:https://github.com/twall/jna#readme
2、把要调用的dll文件拷贝到Java工程路径下,新建一个类,实现Library接口,并在接口类中通过JNA的Native类加载dll文件,如:

EncrypStrTest instance = (EncrypStrTest)Native.loadLibrary("Dll文件的名字", 新建的接口类名.class);

3、在接口类中声明需要在Java中调用的函数(方法),如:

public int add(int a,int b);  public int factorial(int n);

4、完成以上几步就可以在自己的Java类中调用dll文件中的方法了,如:

接口类名.add3,4;

下面是一个获取exe文件版本信息的demo,采用Version进行了进一步的封装

package com.gmi.client;import java.io.File;import java.util.ArrayList;import java.util.List;import com.sun.jna.Pointer;import com.sun.jna.platform.win32.Kernel32;import com.sun.jna.platform.win32.VerRsrc;import com.sun.jna.platform.win32.Version;import com.sun.jna.platform.win32.WinBase;import com.sun.jna.ptr.IntByReference;import com.sun.jna.ptr.PointerByReference;public class GetVersionUsingJNA {    public List<Integer> getVersion(String path){        File fileToCheck = new File(path);        List<Integer> list = new ArrayList<Integer>();        int infoSize = Version.INSTANCE.GetFileVersionInfoSize(fileToCheck.getAbsolutePath(), null);        Pointer buffer = Kernel32.INSTANCE.LocalAlloc(WinBase.LMEM_ZEROINIT, infoSize);        try {            Version.INSTANCE.GetFileVersionInfo(fileToCheck.getAbsolutePath(), 0, infoSize, buffer);            IntByReference outputSize = new IntByReference();            PointerByReference pointer = new PointerByReference();            Version.INSTANCE.VerQueryValue(buffer, "\\", pointer, outputSize);            VerRsrc.VS_FIXEDFILEINFO fileInfoStructure = new VerRsrc.VS_FIXEDFILEINFO(pointer.getValue());            // file version            list.add((int) (fileInfoStructure.dwFileVersionMS.longValue() >> 16));            list.add((int) (fileInfoStructure.dwFileVersionMS.longValue() & 0xffff));            list.add((int) (fileInfoStructure.dwFileVersionLS.longValue() >> 16));            list.add((int) (fileInfoStructure.dwFileVersionLS.longValue() & 0xffff));            // product version            list.add((int) (fileInfoStructure.dwProductVersionMS.longValue() >> 16));            list.add((int) (fileInfoStructure.dwProductVersionMS.longValue() & 0xffff));            list.add((int) (fileInfoStructure.dwProductVersionLS.longValue() >> 16));            list.add((int) (fileInfoStructure.dwProductVersionLS.longValue() & 0xffff));        }        finally  {            Kernel32.INSTANCE.GlobalFree(buffer);        }        return list;    }}

windows本身提供了很多dll控件,也可以使用自己定义的dll文件。这样我们就可以通过JNA进行本地方法的调用了,这样大大扩展了Java程序的面。非常方便的,当然了还有其他方法,不断学习中……

0 0