C++/CLI : Casting from unmanaged enum to managed e

2019-02-01 18:32发布

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.

2条回答
Ridiculous、
2楼-- · 2019-02-01 19:12

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 managed to the native 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.

查看更多
SAY GOODBYE
3楼-- · 2019-02-01 19:37

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.

查看更多
登录 后发表回答