c# - 将 C++ 枚举导入 C#

标签 c# c++

我目前正在创建一个需要与旧 C++ 应用程序交互的新 C# 项目。我需要在 C# 应用中使用的 C++ 应用中已存在错误枚举。

我不想在 C# 中重新声明枚举,因为如果文件没有一起更新,这可能会导致同步问题

话虽如此,我的问题是: 有没有办法让我采用这样声明的枚举:

typedef enum
{
    eDEVICEINT_ERR_FATAL = 0x10001
    ...
} eDeviceIntErrCodes;

并像这样在 C# 程序中使用它:

eDeviceIntErrCodes.eDEVICEINT_ERR_FATAL

最佳答案

在 C/C++ 中,您可以#include 一个包含枚举定义的 .cs 文件。谨慎使用预处理器指令会处理 C# 和 C 之间的语法差异。

例子:

#if CSharp
namespace MyNamespace.SharedEnumerations
{
public
#endif


enum MyFirstEnumeration
{
    Autodetect = -1,
    Windows2000,
    WindowsXP,
    WindowsVista,
    OSX,
    Linux,

    // Count must be last entry - is used to determine number of items in the enum
    Count
};
#if CSharp
public 
#endif

enum MessageLevel
{
    None,           // Message is ignored
    InfoMessage,    // Message is written to info port.
    InfoWarning,    // Message is written to info port and warning is issued
    Popup           // User is alerted to the message
};

#if CSharp
    public delegate void MessageEventHandler(MessageLevel level, string message);
}
#endif

在您的 C# 项目中,设置条件编译符号“CSharp”,确保 C/C++ 构建环境中不存在此类预处理器定义。

请注意,这只会确保两个部分在构建时同步。如果您混合和匹配来自不同构建的二进制文件,则保证失败。

关于c# - 将 C++ 枚举导入 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18765/

相关文章:

c# - lambda 表达式和匿名方法之间的区别 - C#

c++ - 提升日期/时间 microsec_clock 编译不正确

c++ - 多重继承引起的C++拷贝构造函数调用不明确

c++ - 如何使用C++检查tlb文件是否在注册表中注册?

c# - 将 ASN.1 数据转换为公钥需要什么?例如如何确定 OID?

c# - 了解隐藏功能

c# - 无法在网站项目中找到 System.Net.Http

c# - 缺少程序集时,.NET 应用程序静默无法启动

c++ - 将 Bayer RGGB 转换为 CV iplimage (RGB)

C++:奇怪的 std::cout 错误