JNA Java-Native-Access 调用C/C++ dll动态链接库
- 1.框架选择
- 1.1 JNI
- 1.2 JNative
- 1.3 JNA
- 2. JNA使用
- 2.1 pom文件
- 2.2 新建测试类
- 2.3 数据映射
- 参考链接:
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类型 |
char | 8 位整数 | byte |
wchar_t | 与平台相关 | char |
short | 16 位整数 | short |
int | 32 位整数 | int |
int | 布尔标志 | boolean |
enum | 枚举类型 | int (usually) |
long long, __int64 | 64 位整数 | long |
float | 32 位浮点 | float |
double | 64 位浮点 | double |
pointer (e.g. void*) | 与平台相关(32 位或 64 位指向内存的指针) | Buffer Pointer |
pointer (e.g. void*),array | 32 位或 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 | 与Structure | Union |
struct[] | 结构数组,在内存中连续 | Structure[] |
void (*FP)() | 函数指针(Java 或本机) | Callback |
pointer ( *) | 与Pointer | PointerType |
other | 整数类型 | IntegerType |
other | 自定义映射,取决于定义 |