且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在 C# 和非托管 C++ 之间共享枚举声明?

更新时间:2022-12-24 09:26:15

您可以使用单个 .cs 文件并在两个项目之间共享它.#include 在 C++ 中的 .cs 文件应该没问题.

You can use a single .cs file and share it between both projects. #include in C++ on a .cs file should be no problem.

这将是一个示例 .cs 文件:

This would be an example .cs file:

#if !__LINE__    
namespace MyNamespace
{
    public 
#endif

// shared enum for both C, C++ and C#
enum MyEnum { myVal1, myVal2 };

#if !__LINE__
}
#endif

如果你想在一个文件中有多个枚举,你可以这样做(虽然你必须临时定义 public 为 C/C++ 的空):

If you want multiple enums in one file, you can do this (although you have to temporarily define public to be nothing for C / C++):

#if __LINE__
#define public
#else
namespace MyNamespace
{
#endif

    public enum MyEnum { MyEnumValue1, MyEnumValue2 };
    public enum MyEnum2 { MyEnum2Value1, MyEnum2Value2 };
    public enum MyEnum3 { MyEnum3Value1, MyEnum3Value2 };

#if __LINE__
#undef public
#else
}
#endif