Finally.
This was a tough one. The CLR supports three types of value types: auto-layout, sequential, and explicit. A sequential value type is one whose fields are laid out in memory in the same order that they are declared in the type. An explicit value type is one whose fields are explicitly laid out in memory to achieve compatibility with some unmanaged data structure. An auto-layout value type is one where the CLR can rearrange fields to create the most efficient representation based on the target architecture.
Clearly, auto-layout value types are very useful. However, if you want to marshal these things you’re likely to run into trouble. At the very least, you need to allocate enough memory to hold the value type’s fields and then copy the value type into that buffer. The documented way of determining the size of a value type is to use System.Runtime.InteropServices.Marshal.SizeOf().
However, it refuses to report the size of an auto-layout value type. So I have to resort to using the CIL sizeof instruction that provides the same information. But sizeof requires that you specify the type of the value type. So I have to generate a small dynamic method for every auto-layout dynamic that I have to determine the size of:
sizeof <type name>
ret
I execute and then cache the value in the Ruby class object. Yes, it’s a grotesque hack, but it does work. And for the time being, the size of auto-layout value types is fixed for the duration of the process, but this will change in the future.