0
点赞
收藏
分享

微信扫一扫

使用JNA时注意C++的bool类型

窗外路过了谁 2022-04-18 阅读 97

我们通过JNA官方文档,知道一般的类型映射关系。下表是在官方上摘录的一部分信息,文档来源来自于官方文档 http://java-native-access.github.io/jna/4.4.0/javadoc/:

C TypeNative RepresentationJava Type
char8-bit integerbyte
wchar_tplatform-dependentchar
short16-bit integershort
int32-bit integerint
intboolean flagboolean
enumenumeration typeint (usually)
long long, __int6464-bit integerlong
float32-bit floating pointfloat
double64-bit floating pointdouble
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.
longplatform-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 stringsString[]
wchar_t**NULL-terminated array of wide C stringsWString[]
void**NULL-terminated array of pointersPointer[]
struct*
struct
pointer to struct (argument or return) (or explicitly)
struct by value (member of struct) (or explicitly)
Structure
unionsame as StructureUnion
struct[]array of structs, contiguous in memoryStructure[]
void (*FP)()function pointer (Java or native)Callback
pointer (<T> *)same as PointerPointerType
otherinteger typeIntegerType
othercustom mapping, depends on definitionNativeMapped

官方中说明的是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
举报

相关推荐

0 条评论