Native Type | Size | Java Type | Common Windows Types |
char | 8-bit integer | byte | BYTE, TCHAR |
short | 16-bit integer | short | WORD |
wchar_t | 16/32-bit character | char | TCHAR |
int | 32-bit integer | int | DWORD |
int | boolean value | boolean | BOOL |
long | 32/64-bit integer | NativeLong | LONG |
long long | 64-bit integer | long | __int64 |
float | 32-bit FP | float | |
double | 64-bit FP | double | |
char* | C string | String | LPTCSTR |
void* | pointer | Pointer | LPVOID, HANDLE, LPXXX |
<!--Java JNA -->
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>4.1.0</version>
</dependency>
引入JNA:
import com.sun.jna.;
import com.sun.jna.ptr.;
1.构造JNA模拟类
C语言函数:
void function1(int a, int b, const unsigned char* data);
char * function2(float * pVal, char * outString);
void function3(Rect * pRect, Rect rect);
JNA模拟:
public interface MyLibTest extends Library {
//定义结构体
public static class Rect extends Structure {
//公共字段的顺序,必须与C语言中的结构的顺序一致,否则会报错!
public int left;
public int top;
public int right;
public int bottom;
//结构体传指针
public static class ByReference extends Rect implements Structure.ByReference { }
//结构体传值
public static class ByValue extends Rect implements Structure.ByValue{ }
@Override
protected List getFieldOrder() {
return Arrays.asList(new String[]{"left", "top", "right", "bottom"});
}
//加载库文件
MyLibTest INSTANCE = (MyLibTest) Native.loadLibrary("C:\libTest\CLib.dll",MyLibTest.class);
//函数模拟
void function1(int a, int b, char[] data);
String function2(FloatByReference fRef, char [] outString);
void function3(Rect.ByReference pRect, Rect.ByValue rect);
}
调用方式:
char[] arr1 = new char[数组大小];
function1(1, 2, arr1);
char[] arr2 = new char[数组大小];
FloatByReference fRef = new FloatByReference(0.1F);
String result = function2(fRef, arr2);
Rect.ByReference pRect = new Rect.ByReference(); //指针对象
Rect.ByValue rect = new Rect.ByValue(); //传值对象
function3(pRect, rect);
2.JNA模拟C语言数组
C语言函数:
void function1(char * data)
void function2(const unsigned char* data)
JNA模拟:
void function1(char[] data) 或者 void function1(byte[] data)
void function2(char[] data) 或者 void function2(byte[] data)