在一个项目中,我在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之间的大小是不一致的,因为C++中的布尔值为1,而C中的布尔值为4。
有没有人有什么建议可以在不求助于我目前的解决方案的情况下克服这个问题
//#define bool _Bool
#define bool unsigned char这违反了stdbool.h的C99标准
发布于 2008-08-27 01:14:07
我找到了一个符合C99标准的更兼容的stdbool.h实现,从而找到了我自己问题的答案。
#ifndef _STDBOOL_H
#define _STDBOOL_H
#include <stdint.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 */
/* 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项目中提取的。
发布于 2008-08-25 00:10:41
大小不是这里唯一不一致的东西。在C++中,bool是一个关键字,并且C++保证bool可以包含值1或0,其他值都不能包含。C不会给你这样的保证。
也就是说,如果C和C++之间的互操作性很重要,您可以通过为C++定义一个相同的布尔值来模拟C的定制布尔值,并使用它来代替内置布尔值。这将是buggy布尔值和C布尔值和C++布尔值之间的折衷。
发布于 2008-08-25 04:29:45
从逻辑上讲,您不能在带有冲突的bool声明的C和C++之间共享源代码,也不能让它们相互链接。
共享代码和链接的唯一方法是通过中间数据结构。不幸的是,据我所知,您不能修改定义C++程序和C库之间接口的代码。如果可以的话,我建议您使用下面这样的方法:
union boolean {
bool value_cpp;
int value_c;
}; //根据endianness,可能需要填充
其效果是使数据类型在两种语言中具有相同的宽度;需要在两端执行到原生数据类型的转换。将库函数定义中的bool替换为boolean,并在库中摆弄要转换的代码,就完成了。
因此,您需要做的是在C++程序和C库之间创建一个shim。
您必须:
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<int>(b));
return (result==true);
}现在改为调用library_func_1_cpp。
https://stackoverflow.com/questions/25461
复制相似问题