【问题标题】:C# use of enum declared in C++ libraryC# 使用 C++ 库中声明的枚举
【发布时间】:2019-12-14 18:23:40
【问题描述】:

我有一个带有枚举声明的 C++ 库,该库由 C# 应用程序使用。我想在 C# 端使用这个枚举,但它不起作用。如果我在 ProfileType 上按 F12(转到定义),它会打开一个“来自元数据”的文件:

namespace BatchProcessingLib
{
    [CLSCompliant(false)]
    [NativeCppClass]
    public enum ProfileType
    {
    }
}

看起来很空。

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

public enum ProfileType
{
    ProfileTypeCross = 0,
    ProfileTypeDiag = 1,
    ProfileTypeUser = 2
};

我只尝试过 ProfileTypeCross 或 ProfileType.ProfileTypeCross 但我总是遇到编译器错误:

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

有办法吗?

【问题讨论】:

  • C++ 使用 C++ 枚举。 C# 使用 C# 枚举。它们在句法或语义上并不完全兼容。
  • 所以这意味着你做不到?如果不可能,最优雅的解决方案是什么?现在我正在做:“(ProfileType)2”并且编译器很高兴。
  • 您可能会发现这很有帮助...stackoverflow.com/questions/18765/…
  • 来自 MS doc:在原始 C 和 C++ 枚举类型中,未限定的枚举数在声明枚举的整个范围内都是可见的。在作用域枚举中,枚举数名称必须由枚举类型名称限定。 C# 需要范围枚举。

标签: c# c++ enums


【解决方案1】:

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

在 C++ 方面

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

在 C# 方面

enum ProfileType
{
    ProfileTypeCross = 0,
    ProfileTypeDiag = 1,
    ProfileTypeUser = 2
}

从这里我们可以将值直接编组为 enum 类型。

【讨论】:

  • C# 已经“看到” ProfileType 枚举,所以如果我使用相同的枚举名称,我可能会遇到编译器错误,对吧?我现在正在度假,但我稍后会尝试检查一下。
  • 基于您的 C# 应用程序看不到原始枚举的错误,因此它不应该给您任何错误。
  • 它没有看到任何值 ProfileTypeCross 等,但它确实看到了 ProfileType。这就是我提出的解决方案有效的原因。
【解决方案2】:

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

https://www.geeksforgeeks.org/enum-classes-in-c-and-their-advantage-over-enum-datatype/

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

enum class ProfileType
{
    ProfileTypeCross = 0,
    ProfileTypeDiag = 1,
    ProfileTypeUser = 2
};   

尚未尝试,但应该可以。感谢 Regis 指出这一点,并且另一个 stackoverflow 线程也讨论了这个问题:

Importing C++ enumerations into C#

【讨论】:

    【解决方案3】:

    我最终使用了这个可行的解决方案:

    /// @remarks C++ enums are incompatible with C# so you need to go and check the corresponding C++ header file :-|
    if (profileType == (ProfileType)0)
    {
    

    这样我就不必在 C# 端重新声明枚举,并且保留到原始声明的链接,即使我不能使用对用户更友好的文本值名称。

    编辑:找到更好的解决方案,寻找我的其他答案...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-20
      • 2020-07-19
      • 2015-04-26
      • 2014-08-22
      • 2010-09-09
      相关资源
      最近更新 更多