Basically I need to expose several constants from unmanaged C++ to my C# library. The following approach works, but I think it smells:
In my unmanaged C++ code:
class Mappings
{
public:
static const int North = 0 ;
static const int West = 1 ;
static const int East = 2 ;
static const int South = 3 ;
In my managed C++ layer:
public:
static const int North = Mappings::North ;
static const int West = Mappings::West ;
static const int East = Mappings::East ;
static const int South = Mappings::South ;
Is there a cleaner/shorter way, so that I do not have to duplicate my code twice?
Use the
public enum classkeywords to declare a managed enumeration type. And yes, this is ugly since you cannot export the native C++ enumeration. Repeating yourself is unfortunately required.C++11 adopted the
enum classkeyword as well but it is still distinct from the managed version. This caused a syntax ambiguity in C++/CLI since both language flavors now use the same keywords. The compiler can see the distinction from the accessibility keyword (usepublicorprivate), it is not valid for native C++.