Search code examples
c#c++enumsnativemanaged

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?


Solution

  • 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