jna调用dll动态库

dll 动态链接库是微软公司在微软Windows操作系统中,实现共享函数库概念的一种方式。
jna 是java native access的简称,用他可以调用C、C++代码,特别是windows中强大的库文件(dll,在linux下是so文件),这样java就可以操控底层的一些东西.
首先,使用mavaen导入jna jar包
<!-- jna --> <dependency> <groupId>com.sun.jna</groupId> <artifactId>jna</artifactId> <version>3.0.9</version> </dependency>

首先使用系统自带dll文件进行调用测试

package com.crux.posms;

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

public class test {
    public interface CLibrary extends Library {
        // DLL文件默认路径为项目根目录,若DLL文件存放在项目外,请使用绝对路径。(此处:(Platform.isWindows()?"msvcrt":"c")指本地动态库msvcrt.dll)  Native.loadLibrary此时为c:/windows/system32 下
        CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows()?"msvcrt":"c"),
                CLibrary.class);
        // 声明将要调用的DLL中的方法,可以是多个方法(此处示例调用本地动态库msvcrt.dll中的printf()方法)
       	void printf(String format, Object... args);  //这个方法是dll中的方法,要使用必须在此处声明一下
        }
    public static void main(String[] args) {
       CLibrary.INSTANCE.printf("Hello, World!");
        }
}

运行结果
在这里插入图片描述
在测试过程中使用本地动态库没有问题,为了证实java确实可以调用其他语言方法(毕竟cv程序员见识少),便自行写了一个简单dll进行测试.
使用vs 创建了一个c++程序
首先选择新建项目选择
在这里插入图片描述
而后选则dll程序
在这里插入图片描述
新建项目后创建两个文件,test.h 头文件 test.cpp源文件.头文件里一般就类似公共文件,cppl里使用#include就可以引用.在这里头文件内容为导出方法作用是可以被其他语言所调用。源文件里面的就是调用的方法
test.h文件内容

extern "C" _declspec(dllexport) int _stdcall add(int a,int b);

test.cpp文件内容

#include "stdafx.h"
#include "test.h"
int _stdcall add(int a,int b){
 return a+b;
}

然后有一个重要步骤,此时若直接运行生成的dll默认是32位的一定要根据自己jdk版本确定好要生成的版本,博主在此就卡了一上午报加载不到文件。
在这里插入图片描述

然后运行生成dll文件放入你要放入的目录位置

package com.crux.posms;

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

public class test {
    public interface CLibrary extends Library {
        // DLL文件默认路径为项目根目录,若DLL文件存放在项目外,请使用绝对路径。(此处:(Platform.isWindows()?"msvcrt":"c")指本地动态库msvcrt.dll)
        CLibrary INSTANCE = (CLibrary) Native.loadLibrary("E:\\a\\test",
                CLibrary.class);  //我将dll放入e盘下,记得这里目录路径一定要为 \\
             int add(int a,int b);
       
    }
    public static void main(String[] args) {
               int b=CLibrary.INSTANCE.add(3,5);
       		 System.out.println(b);
            }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值