与stdbool.h C ++接口

在一个项目中,我在C ++和一个使用stdbool.h的C库之间进行接口。

#ifndef _STDBOOL_H #define _STDBOOL_H /* C99 Boolean types for compilers without C99 support */ /* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */ #if !defined(__cplusplus) #if !defined(__GNUC__) /* _Bool builtin type is included in GCC */ typedef enum { _Bool_must_promote_to_int = -1, false = 0, true = 1 } _Bool; #endif #define bool _Bool #define true 1 #define false 0 #define __bool_true_false_are_defined 1 #endif #endif 

一些结构有bool成员。 因此,如果我将这些结构中的一个定义为C ++函数中的局部变量并将其传递给C函数,则C ++和C之间的大小不一致,因为bool在C ++中是一个再见,在C中是4个。

有没有人有任何建议如何克服这个问题而不诉诸我目前的解决方案

 //#define bool _Bool #define bool unsigned char 

这符合stdbool.h的C99标准

通过找到符合C99标准的更兼容的stdbool.h实现,我找到了自己问题的答案。

 #ifndef _STDBOOL_H #define _STDBOOL_H #include  /* C99 Boolean types for compilers without C99 support */ /* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */ #if !defined(__cplusplus) #if !defined(__GNUC__) /* _Bool builtin type is included in GCC */ /* ISO C Standard: 5.2.5 An object declared as type _Bool is large enough to store the values 0 and 1. */ /* We choose 8 bit to match C++ */ /* It must also promote to integer */ typedef int8_t _Bool; #endif /* ISO C Standard: 7.16 Boolean type */ #define bool _Bool #define true 1 #define false 0 #define __bool_true_false_are_defined 1 #endif #endif 

这取自Ada Class Library项目。

尺寸不是唯一不一致的东西。 在C ++中,bool是一个关键字,C ++保证bool可以保存1或0的值而不是其他值。 C不会给你这个保证。

也就是说,如果C和C ++之间的互操作性很重要,你可以通过为C ++定义一个相同的布尔值并使用它而不是内置bool来模拟C的定制布尔值。 这将是一个错误的布尔值与C布尔值和C ++布尔值之间的相同行为之间的权衡。

从逻辑上讲,您无法在C和C ++之间共享具有冲突的bool声明的源代码,并让它们相互链接。

您可以通过中间数据结构共享代码和链接的唯一方法。 不幸的是,根据我的理解,您无法修改定义C ++程序和C库之间接口的代码。 如果可以,我建议使用类似的东西:

 union boolean { bool value_cpp; int value_c; }; 

//取决于字节顺序,可能需要填充

其效果是使两种语言中的数据类型具有相同的宽度; 需要在两端执行到本机数据类型的转换。 在库函数定义中交换使用bool for boolean,在库中调整代码进行转换,然后就完成了。

所以,你要做的就是在C ++程序和C库之间创建一个垫片 。

你有:

 extern "C" bool library_func_1(int i, char c, bool b); 

你需要创建:

 bool library_func_1_cpp(int i, char c, bool b) { int result = library_func_1(i, c, static_cast(b)); return (result==true); } 

现在调用library_func_1_cpp。