What is the correct way of casting (in C++/CLI) from a native code enum
to a managed code enum
which contain the same enum
values? Is there any difference with using the C# way of casting like for example (int)
in C++/CLI.
Asked
Active
Viewed 2.5k times
2 Answers
43
Assuming your native code is
enum shape_type_e
{
stUNHANDLED = 0, //!< Unhandled shape data.
stPOINT = 1 //!< Point data.
...
};
and your managed code is
public enum class ShapeType
{
Unhandled = 0,
Point = 1,
...
};
You can cast from the native to the managed using
shape_type_e nativeST = stPOINT;
ShapeType managedST = static_cast<ShapeType>(nativeST);
Debug.Assert(managedST == ShapeType::Point);
I always use static_cast
, not the C# way of casting.
-
2From the above code, I suppose you are casting from native to managed enum. What about the other way round from managed to native? – Lopper Dec 10 '09 at 06:53
-
7Static cast is your friend both ways ... nativeST = static_cast
(managedST); – mcdave Dec 10 '09 at 07:01 -
Based on your comment to @Lopper, could you then change the text in your answer to clarify that the example is demonstrating native-to-managed (and not the other way around as it currently states). – Glenn Slayden Jan 21 '17 at 23:05
1
It depends. for example, if you have a CLI enum that has an underlying type of ushort, it cannot hold a vallue of 257. By default the CLI enum is based on int, which should be fine in most cases. If your native C++ code use unsigned 32bit ints/64bit ints as the underlying type if enums, switch the base of your CLI enum to UInt32, long or ulong.

Sheng Jiang 蒋晟
- 15,125
- 2
- 28
- 46
-
3I won't have this issue because both enum are of type int. But which type of cast should be used in this case? Should it be const_cast, static_cast, dynamic_cast, reinterpret_cast, safe_cast or just the C# cast (an example is (int))? – Lopper Dec 10 '09 at 01:40