我想創建一個包含頭文件sdk.h的公共API和一個編譯後的DLL與實現的SDK。在SDK API中使用枚舉參數和返回值是否安全?
If the code looks like:
//////////
// sdk.h
//////////
enum eAction
{
Action1,
Action2,
Action3
};
class Item
{
protected:
virtual ~Item(){}
public:
virtual void Do(eAction action) = 0;
virtual void Release() = 0;
};
extern "C"
{
Item * CreateItem();
}
//////////
// sdk.cpp
//////////
class ItemImpl: public Item
{
public:
virtual void Do(eAction action)
{
printf("%d", (int)action);
// do something
}
virtual void Release()
{
delete this;
}
};
Item * CreateItem()
{
return new ItemImpl;
}
//////////
// main.cpp client side
//////////
int main(int argc, char* argv[])
{
Item *pItem = CreateItem();
pItem->Do(Action1);
pItem->Release();
return 0;
}
// The file sdk.h is the public API.
// The file sdk.cpp is the implementation and it is compiled to sdk.dll.
// The file main.cpp is the client code that uses the SDK.
我的問題是:
是可以安全使用枚舉PARAMS和公共API的返回值(方法DO(動作))如果SDK和客戶端代碼與不同的編譯器編譯的?例如SDK使用VC編譯,客戶端代碼使用gcc編譯。是否有可能不同的編譯器使用不同的大小(2,4或8字節)來表示枚舉?
標準允許使用不同大小,重要的問題(我不知道答案,因此這是一條評論)是您所關心的平臺上的C++ ABI(s)是否指定如何確定枚舉的基礎類型。如果您不知道您關心的平臺,那麼您必須將其視爲不屬於ABI的一部分,因此您無法將'enum'跨越可執行邊界傳遞超過您可以傳遞'std :: string'。 –
我認爲這是一個現實生活衝突的例子:http://osdir.com/ml/android-ndk/2010-10/msg00559.html。假設帖子爲真,默認情況下,Android的工具鏈被配置爲使用'short'枚舉,但是一些'libstdC++'dll至少使用'int'。因此,除非用'-fno-short-enums'編譯,否則符合「short」的枚舉在兩者之間是不兼容的。所以如果你的「兩個編譯器」都是GCC,但是有一個沒有'-fshort-enums',那麼你的建議可能是不安全的。如果小於'int'的參數作爲'int'傳遞,您可能會失去它。 –