C# 使用C++库中声明的枚举
C# use of enum declared in C++ library
我有一个带有枚举声明的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# 端重新声明枚举,并且保留指向原始声明的链接,即使我不能使用更加用户友好的文本值名称。
编辑:找到更好的解决方案,寻找我的另一个答案...
相关文章:
- 访问在 C++ 结构中声明的枚举变量
- 如何使用默认值将枚举声明为 extern
- 如何转发声明枚举?
- 如何将枚举类转发声明为模板化类的内部类?
- 枚举前向声明与头文件
- C++:如何在声明枚举类的模板类主体之外定义枚举类?
- 在C++代码中使用的 C 标头中向前声明枚举
- 在哪里声明枚举
- 在模板参数内向前声明枚举类
- 在C++14中,在哪个作用域中声明了重新声明枚举的非范围枚举器
- 在C中定义的C++中正向声明枚举
- 在不膨胀命名空间的情况下在C++中声明枚举的好方法
- 声明枚举标识符的基础类型
- 为什么在向前声明枚举时必须提供枚举的大小?
- 前向声明枚举类不起作用
- 在运行时有条件地声明枚举(C++)
- 我可以传递前向声明枚举的值吗?
- c++ -对声明枚举感到困惑
- c++:在类内部从外部声明枚举器,以便可以在私有成员中使用
- 在声明枚举之前使用它