C# 使用C++库中声明的枚举

C# use of enum declared in C++ library

本文关键字:声明 枚举 使用 C++      更新时间:2023-10-16

我有一个带有枚举声明的C++库,该库由 C# 应用程序使用。我想在 C# 端使用此枚举,但它不起作用。如果我在配置文件类型上按 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++enums

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

在C++面

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

在 C# 端

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

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

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

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 指出这一点,另一个堆栈溢出线程也在讨论这个问题:

将C++枚举导入 C#

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

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

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

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