JNA(Java-Native-Access)调用C/C++ dll动态链接库

1.框架选择

1.1 JNI

1、编写静态方法(用java声明)
2、编译生成class文件
3、编译生成h文件
4、编写C文件(用C/C++实现)
5、配置NDK
6、配置so库
7、在Activity调用(Java调用C/C++)。

1.2 JNative

1、下载Jnative.jar,下载地址如下:
  http://nchc.dl.sourceforge.net/sourceforge/jnative/JNative.jar
  把JNativeCpp.dll放在c:\windows\system32目录下;把要调用的dll文件也放在c:\windows\system32目录下。
2、编码调用dll

1.3 JNA

GitHub:https://github.com/java-native-access/jna
5.5版本文档:https://java-native-access.github.io/jna/5.5.0/javadoc/overview-summary.html#loading

1、下载 jna.jar,jna-platform.jar放入到java项目类路径下;
2、创建一个接口继承Library;
3、声明方法,方法的返回值和参数要和本地dll对应;
4、实例化接口实例;
5、调用接口;

2. JNA使用

2.1 pom文件

<!-- 调用C/C++ dll动态链接库 -->
<dependency>
    <groupId>net.java.dev.jna</groupId>
    <artifactId>jna</artifactId>
    <version>5.5.0</version>
</dependency>

<dependency>
    <groupId>net.java.dev.jna</groupId>
    <artifactId>jna-platform</artifactId>
    <version>5.5.0</version>
</dependency>

2.2 新建测试类

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

public class JnaTest {
// 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.load((Platform.isWindows() ? "msvcrt" : "c"),
                        CLibrary.class);

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

    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]);
        }
    }
}

2.3 数据映射

C语言类型本地表示Java类型
char8 位整数byte
wchar_t与平台相关char
short16 位整数short
int32 位整数int
int布尔标志boolean
enum枚举类型int (usually)
long long, __int6464 位整数long
float32 位浮点float
double64 位浮点double
pointer (e.g. void*)与平台相关(32 位或 64 位指向内存的指针)Buffer Pointer
pointer (e.g. void*),array32 位或 64 位指向内存(参数/返回)连续内存(结构成员)的指针

[] (array of primitive type)

long平台相关(32 位或 64 位整数)NativeLong
const char*NUL 终止的阵列(本机编码或jna.encoding)String
const wchar_t*NUL 端接的阵列(单码)WString
char**C 字符串的 NULL 终止数组String[]
wchar_t**宽 C 字符串的 NULL 终止数组WString[]
void**空端指针数组Pointer[]
struct*, struct指向结构(参数或返回) (或显式)按值 (结构成员) (或显式)结构的指针)Structure
union与StructureUnion
struct[]结构数组,在内存中连续Structure[]
void (*FP)()函数指针(Java 或本机)Callback
pointer ( *)与PointerPointerType
other整数类型IntegerType
other自定义映射,取决于定义NativeMapped

参考链接:

jna教程:【简书】China第一程序员
https://www.jianshu.com/p/24174203c3d7
调试问题:【简书】长脖子树
https://www.jianshu.com/p/ead89497c403

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jack魏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值