runtime: Marshal.SizeOf throws for enum types

Attempting to call Marshal.SizeOf for an enum type currently results in the following:

Type '*' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.
  + System.Runtime.InteropServices.Marshal.SizeOfHelper(System.Type, bool)

As far as I am aware, enums are considered to be blittable as they are internally just a value type that contains a single field of a blittable type (generally this is int32). However, there isn’t anything explicit about enum marshalling in https://docs.microsoft.com/en-us/dotnet/framework/interop/blittable-and-non-blittable-types.

I would expect the above call to succeed and for there to be documentation on the blittability of enum types.

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Comments: 17 (15 by maintainers)

Most upvoted comments

According to ECMA 335, enums can actually have an underlying type of char or bool, so they’re not always blittable. This’ll take some more investigation to make sure we handle this correctly.

what would you intuitively expect the size to be?

The size of the underlying type, i.e. the following should hold:

sizeof(MyEnum) == Marshal.SizeOf<MyEnum>()

If we do something here, we should make all the Marshal APIs consistent. E.g. Marshal.PtrToStructure should handle enums too.

Yep, the builtin runtime interop is full of worms. I would treat this issue with very low priority since we discourage use of these APIs anyway. There is a lot more other interesting interop work we can be spending time on…

This might be failing because it looks the C# compiler is emitting enums as auto layout, rather than sequential as it does for other value types.

“14.3 Enums […] they shall have auto field layout (§10.1.2)”