C#使用C+中声明的enum+;图书馆 我有一个带有EnUM声明的C++库,这个库是由C应用程序使用的。我想在C#端使用此枚举,但它不起作用。如果我在ProfileType上按F12键(转到定义),它将打开一个“来自元数据”文件,其中包含: namespace BatchProcessingLib { [CLSCompliant(false)] [NativeCppClass] public enum ProfileType { } }

C#使用C+中声明的enum+;图书馆 我有一个带有EnUM声明的C++库,这个库是由C应用程序使用的。我想在C#端使用此枚举,但它不起作用。如果我在ProfileType上按F12键(转到定义),它将打开一个“来自元数据”文件,其中包含: namespace BatchProcessingLib { [CLSCompliant(false)] [NativeCppClass] public enum ProfileType { } },c#,c++,enums,C#,C++,Enums,看起来很空 在C++头文件中声明为: public enum ProfileType { ProfileTypeCross = 0, ProfileTypeDiag = 1, ProfileTypeUser = 2 }; 我尝试了ProfileTypeCross或ProfileType.ProfileTypeCross,但始终出现编译器错误: Error CS0117 'ProfileType' does not contain a definition for

看起来很空

在C++头文件中声明为:

public enum ProfileType
{
    ProfileTypeCross = 0,
    ProfileTypeDiag = 1,
    ProfileTypeUser = 2
};
我尝试了ProfileTypeCross或ProfileType.ProfileTypeCross,但始终出现编译器错误:

Error   CS0117  'ProfileType' does not contain a definition for 'ProfileTypeUser'  

有办法吗?

我最终使用了这个有效的解决方案:

/// @remarks C++ enums are incompatible with C# so you need to go and check the corresponding C++ header file :-|
if (profileType == (ProfileType)0)
{
这样,我就不必在C#端重新声明enum,而且我保留了一个到原始声明的链接,即使我不能使用用户友好得多的文本值名称


编辑:找到一个更好的解决方案,寻找我的另一个答案…

C++
enum
是32位宽的,因此您可以再次在C#中声明
enum
,并从那里使用它

在C++侧

enum ProfileType
{
    ProfileTypeCross = 0,
    ProfileTypeDiag = 1,
    ProfileTypeUser = 2
};
在C侧


从这里,我们可以直接将值封送到
enum
类型。

我确实为此发布了一个折衷的解决方案,但显然在C++11中有一个更好的解决方案,使用enum classes,一个强类型和强范围的enum变体:

<> P>所以,在C++方面,解决方案是:

enum class ProfileType
{
    ProfileTypeCross = 0,
    ProfileTypeDiag = 1,
    ProfileTypeUser = 2
};   
我还没试过,但应该能用。感谢Regis指出这一点,另一个stackoverflow线程也在讨论这个问题:


C++使用C++枚举。C#使用C#枚举。它们在语法或语义上都不完全兼容。所以这意味着你不能这么做?如果不可能,最优雅的解决方案是什么?现在我正在做:“(ProfileType)2”,编译器很高兴。你可能会发现这很有用。。。从MS doc:在原始的C和C++的枚举类型中,不合格枚举器在枚举声明的范围内可见。在作用域枚举中,枚举器名称必须由枚举类型名称限定。C#需要作用域枚举。C#已经“看到”了ProfileType枚举,所以如果我使用相同的枚举名,可能会出现编译器错误,对吗?我现在正在度假,但我稍后会尝试检查。根据提供的错误,您的C#应用程序没有看到原始枚举,因此它不会给您任何错误。它没有看到任何ProfileTypeCross等值,但它确实看到了ProfileType。这就是我提出的解决方案有效的原因。
enum class ProfileType
{
    ProfileTypeCross = 0,
    ProfileTypeDiag = 1,
    ProfileTypeUser = 2
};