我们通过JNA官方文档,知道一般的类型映射关系。下表是在官方上摘录的一部分信息,文档来源来自于官方文档 http://java-native-access.github.io/jna/4.4.0/javadoc/:
C Type | Native Representation | Java Type |
char | 8-bit integer | byte |
wchar_t | platform-dependent | char |
short | 16-bit integer | short |
int | 32-bit integer | int |
int | boolean flag | boolean |
enum | enumeration type | int (usually) |
long long, __int64 | 64-bit integer | long |
float | 32-bit floating point | float |
double | 64-bit floating point | double |
pointer (e.g. void*) | platform-dependent (32- or 64-bit pointer to memory) | Buffer Pointer |
pointer (e.g. void*), array | 32- or 64-bit pointer to memory (argument/return) contiguous memory (struct member) | <P>[] (array of primitive type) |
In addition to the above types, which are supported at the native layer, the JNA Java library automatically handles the following types. All but NativeMapped and NativeLong are converted to Pointer before being passed to the native layer. | ||
long | platform-dependent (32- or 64-bit integer) | NativeLong |
const char* | NUL-terminated array (native encoding or jna.encoding ) | String |
const wchar_t* | NUL-terminated array (unicode) | WString |
char** | NULL-terminated array of C strings | String[] |
wchar_t** | NULL-terminated array of wide C strings | WString[] |
void** | NULL-terminated array of pointers | Pointer[] |
struct* struct | pointer to struct (argument or return) (or explicitly) struct by value (member of struct) (or explicitly) | Structure |
union | same as Structure | Union |
struct[] | array of structs, contiguous in memory | Structure[] |
void (*FP)() | function pointer (Java or native) | Callback |
pointer (<T> *) | same as Pointer | PointerType |
other | integer type | IntegerType |
other | custom mapping, depends on definition | NativeMapped |
官方中说明的是C-Type,而不是C++ Type,说明JNA本身对C++其实是不完全支持的。bool类型恰巧是C++中独有的。
如果你的DLL是通过extern C的形式输出,参数中或者返回值为C++的bool类型,经过JNA转换之后并不会转换为integer或者boolean类型,而是转换成了char类型。
其实这一点符合C++本身对于bool的定义,bool在内存中本身存储空间仅占用1个字节。在C++语法中,如果将char类型强转为bool,不会提示warning;而如果将int强转为bool,则会提示数据丢失的warning
但是这个JNA使用C++ bool类型非常容易在跨平台编程的时候造成非常大的麻烦。更为推荐的方法是C++在编写DLL库时,对外符号禁止任何bool类型作为传参或者返回值;而对内符号可以适当放宽这个要求,但是为了保持工程的一致性,一般更推荐使用BOOL自定义宏来完成这个工作。
#ifndef BOOL
#define BOOL bool
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif