目录
Introduction to JNA
Java Native Access (JNA) is a community-developed library providing Java programs an easy access to native shared libraries (.dll files on windows, .so files on Unix ...)
JNA is a mature library with dozens of contributors and hundreds of commercial and non-commercial projects that use it.
Who use JNA?
Features
- Automatic mapping from Java to native functions, with simple mappings for all primitive data types
- Runs on most platforms which support Java
- Automatic conversion between C and Java strings, with customizable encoding/decoding
- Structure and Union arguments/return values, by reference and by value
- Function Pointers, (callbacks from native code to Java) as arguments and/or members of a struct
- Auto-generated Java proxies for native function pointers
- By-reference (pointer-to-type) arguments
- Java array and NIO Buffer arguments (primitive types and pointers) as pointer-to-buffer
- Nested structures and arrays
- Wide (wchar_t-based) strings
- Native long support (32- or 64-bit as appropriate)
- Demo applications/examples
- Supported on 1.4 or later JVMs, including JavaME (earlier VMs may work with stubbed NIO support)
- Customizable marshalling/unmarshalling (argument and return value conversions)
- Customizable mapping from Java method to native function name, and customizable invocation to simulate C preprocessor function macros
- Support for automatic Windows ASCII/UNICODE function mappings
- Varargs support
- Type-safety for native pointers
- VM crash protection (optional)
- Optimized direct mapping for high-performance applications.
- COM support for early and late binding.
- COM/Typelib java code generator.
Why JNA
JNA(Java Native Access)是一个开源的Java框架,是Sun公司推出的一种调用本地方法的技术,是建立在经典的JNI基础之上的一个框架。之所以说它是JNI的替 代者,是因为JNA大大简化了调用本地方法的过程,使用很方便,基本上不需要脱离Java环境就可以完成。
不需要手写访问java变量和函数的方法
下载jar
Hello World示例
其中代码有些不友好,环境介绍只有一句:
Begin by downloading the latest release of JNA and referencing jna.jar
in your project's CLASSPATH
如果不熟悉会出现如下问题:
1. 编译时出现cannot find symbol com.sun.jna.Library问题
需要在javac和java 中指定-classpath
javac -classpath .:jna.jar -g com/sun/jna/examples/HelloWorld.java
java -classpath .:jna.jar com.sun.jna.examples.HelloWorld
2. 运行时出现java.lang.NoClassDefFound问题
问题出在package com.sun.jna.examples
请放文件在如下目录:
/examples
jna.jar
/com
/sun
/jna
/examples
HelloWorld.java
参考java - JNA 示例程序 java.lang.NoClassDefFoundError - IT工具网https://www.coder.work/article/1410839
其他的代码解释:
总结:对比JNI和JNA方法
JNI的方式
JNA的方式