Jaa


Sharing enums across C# and C++

On an internal DL someone asked a question about how folks share enums between C++ and C# code when required (e.g. common error codes for a large project that use both native code and C#).

There was a very interesting answer given by one person. He simply asked why don't you define it in a .cs file and #include that file in your C++ code. I initially thought what the hell is he talking about and then it struck me that C++ and C# is not just similar but in some context they are exactly the same. Consider the following enum definition in a .cs files

 // File Enum.cs
namespace EnumShare
{
    enum MyEnum
    {
        a = 1,
        b = 2,
        c = 3,
    };
}

This can be simply included in a C# project to be built normally. However, it can also be pulled into C++ code as follows

 #include "..\EnumShare\Enum.cs"

using namespace EnumShare;

int Foo()
{
    cout << a << endl;

}

Note that I could directly pull in the C# code because the syntax matches that of C++ :)

I thought that this was a rather interesting usage.

Comments

  • Anonymous
    August 26, 2007
    The comment has been removed

  • Anonymous
    August 26, 2007
    Would it not be more common to find the set of such "constants" in a separate DLL? If so, including the actual file where the enum is defined wouldn't be appropriate. What would you suggest then?

  • Anonymous
    August 26, 2007
    Acabo de leer en uno de los blogs a los que estoy suscrito un tema que considero bastante curioso e interesante

  • Anonymous
    August 27, 2007
    The comment has been removed

  • Anonymous
    August 29, 2007
    The comment has been removed

  • Anonymous
    July 25, 2008
    Intresting....My project requires this

  • Anonymous
    November 24, 2010
    There is a comma too many on the third enum value, you want:        c = 3 instead of        c = 3,