12

I need to create a wrapper between C++ and C#. I have a function very similar to this:

virtual SOMEINTERFACE* MethodName(ATTRIBUTE_TYPE attribType = ATTRIBUTE_TYPE::ATTRIB_STANDARD) = 0;

The enum is declared like this:

enum class ATTRIBUTE_TYPE { 
    ATTRIB_STANDARD, 
    ATTRIB_LENGTH 
};

How do I wrap that ATTRIBUTE_TYPE enum?

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
Rock3rRullz
  • 357
  • 1
  • 4
  • 21
  • What is the underlying type for `ATTRIBUTE_TYPE`? – Mgetz Mar 04 '14 at 15:51
  • Just a simple enum: enum class ATTRIBUTE_TYPE { ATTRIB_STANDARD, ATTRIB_LENGTH }; – Rock3rRullz Mar 04 '14 at 15:56
  • 3
    insofar as you specify the type on the enum in C# and C++ (and they are the same) you should be able to use the enum directly in the P/Invoke. Just be forewarned that not all the C++ and C# types that share names are the same, e.g. `long` in C# is an int64 whereas in C++ it's just an int32. – Mgetz Mar 04 '14 at 16:07
  • Related http://stackoverflow.com/q/5584160/332733 – Mgetz Mar 04 '14 at 16:09
  • @Mgetz The 'long' type is 32-bits in Microsoft C++; it follows the architecture size most elsewhere (ex. GCC). – codesniffer Dec 29 '18 at 05:10

1 Answers1

20

Your C++ enum is defined like this:

enum class ATTRIBUTE_TYPE { 
    ATTRIB_STANDARD, 
    ATTRIB_LENGTH 
};

By default, enum class types are int sized. Which means that you can translate this to C# like so:

enum ATTRIBUTE_TYPE { 
    ATTRIB_STANDARD, 
    ATTRIB_LENGTH 
};

That's all there is to it. A C# enum is blittable and this C# enum maps exactly on to your C++ enum.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490