Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to share an enum declaration between C# and unmanaged 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 };

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?

like image 540
sean e Avatar asked Jun 05 '09 04:06

sean e


People also ask

How do I view enums in another file?

You have to put the enum in a header file, and use #include to include it in the source file.

Can you inherit from an enum?

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.

Can we have enum inside enum in C?

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.

Can we change enum values in C?

You can change default values of enum elements during declaration (if necessary).


1 Answers

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
like image 189
jjxtra Avatar answered Oct 02 '22 18:10

jjxtra