是否可以在 C# 和非托管 C++ 之间共享枚举声明? [英] Is it possible to share an enum declaration between C# and unmanaged C++?
问题描述
有没有办法在本机(非托管)C++ 和(托管)C# 之间共享枚举定义?
Is there a way to share an enum definition between native (unmanaged) C++ and (managed) C#?
我在完全非托管的代码中使用了以下枚举:
I have the following enum used in completely unmanaged code:
enum MyEnum { myVal1, myVal2 };
我们的应用程序有时会使用托管组件.该 C# 组件通过托管的 C++ 互操作 dll(来自本机 dll)获取作为整数的枚举项值.(互操作 dll 仅在需要 C# 组件时才加载.)C# 组件复制了枚举定义:
Our application sometimes uses a managed component. That C# component gets the enum item values as ints via a managed C++ interop dll (from the native dll). (The interop dll only loads if the C# component is needed.) The C# component has duplicated the enum definition:
public enum MyEnum { myVal1, myVal2 };
有没有办法在不将本机 C++ dll 转换为托管 dll 的情况下消除重复?
Is there a way to eliminate the duplication without turning the native C++ dll into a managed dll?
推荐答案
您可以使用单个 .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
这篇关于是否可以在 C# 和非托管 C++ 之间共享枚举声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!