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 };
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 };
Is there a way to eliminate the duplication without turning the native C++ dll into a managed dll?
You have to put the enum in a header file, and use #include to include it in the source file.
Enums cannot inherit from other enums. In fact all enums must actually inherit from System. Enum . C# allows syntax to change the underlying representation of the enum values which looks like inheritance, but in actuality they still inherit from System.
It is not possible to have enum of enums, but you could represent your data by having the type and cause separately either as part of a struct or allocating certain bits for each of the fields.
You can change default values of enum elements during declaration (if necessary).
You can use a single .cs file and share it between both projects. #include
in C++ on a .cs file should be no problem.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With