我目前正在创建一个需要与旧 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/