Are .net Enums blittable types? (Marshalling)

前端 未结 3 1713
名媛妹妹
名媛妹妹 2021-01-03 02:18

Apparently there\'s a list of blittable types and so far I don\'t see Enums specifically on it. Are they blittable in general? Or does it depend on whether they are declared

3条回答
  •  鱼传尺愫
    2021-01-03 03:05

    Aliostad is correct. For example, if one tries to execute the statement:

    int size = Marshal.SizeOf( System.ConsoleColor.Red );
    

    then an ArgumentException is thrown, with the message:

    Type 'System.ConsoleColor' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.

    However, the statement:

    int size = Marshal.SizeOf( (int)System.ConsoleColor.Red );
    

    works just fine as one would expect.

    Likewise, the statement:

    int enumSize = Marshal.SizeOf( typeof(ConsoleColor) );
    

    fails, but the statement:

    int enumSize = Marshal.SizeOf( Enum.GetUnderlyingType( typeof(ConsoleColor) ) );
    

    succeeds.

    Unfortunately, Microsoft's documentation for Marshal.SizeOf( object ) is deficient; that page doesn't even include ArgumentException in the list of possible exceptions. The doc for Marshal.SizeOf( Type ) lists ArgumentException, but only says that it's thrown when the type is generic (which is true, but doesn't cover the above example).

    (Also, the documentation for the enum keyword, the Enum class, and Enumeration Types in the C# Programming Guide makes no mention at all about whether an enum value is directly blittable.)

提交回复
热议问题