2008-08-24 44 views
13

在一個項目中,我在C++和使用stdbool.h定義的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

回答

10

我找到了符合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項目。

+0

更新:_Bool現在在VS2013中定義,所以我們還需要檢查_MSC_VER <1800。http://msdn.microsoft.com/en-us/library/hh409293.aspx – Tom 2014-12-02 15:47:24

1

尺寸C99標準是不是會不一致這裏唯一的事情。在C++中,bool是一個關鍵字,C++保證bool可以保存1或0的值,而不是其他值。 C不給你這個保證。這就是說,如果C和C++之間的互操作性非常重要,那麼可以通過爲C++定義一個相同的布爾類型來代替內置的布爾類型來模擬C的定製布爾值。這將是一個錯誤的布爾和C布爾和C++布爾之間的相同行爲之間的折衷。

0

從邏輯上講,您無法在C和C++之間共享源代碼,併爲bool聲明衝突並讓它們彼此鏈接。

您可以共享代碼和鏈接的唯一方法是通過中間數據結構。不幸的是,據我所知,你不能修改定義你的C++程序和C庫之間的接口的代碼。如果可以,我建議使用這樣的:根據endianness

它的影響將是使數據類型在兩種語言相同的寬度

union boolean { 
    bool value_cpp; 
    int value_c; 
}; 

//填充可能是必要的;轉換爲本地數據類型需要在兩端執行。在庫函數定義中交換布爾值的使用,在庫中轉換代碼,然後就完成了。

因此,你將不得不做的是在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。