views:

181

answers:

1

Is it possible to create a method like BitConverter.GetBytes() that accepts as input also a parameter of type Object, without using Marshaling as done here?

Or the only solution, if a type Object is given as input, is to implement a case on all available .NET value types?

+2  A: 

No it isn't. The internal layout of a class or struct is undiscoverable. Marshaling is required, guided by a [StructLayout], to convert that undocumented layout to a known one. The JIT compiler readily takes advantage of this, it re-orders the fields in a struct for example to get them properly aligned and require the minimum of storage. This defeats any tricks that messes with unmanaged pointers. The simple value types behave predictably, but they are already well covered by BitConverter. Structures are your nemesis.

This is one reason why it took so long for memory-mapped files to be supported by the .NET framework. But they'll be available in .NET 4.0, you could take advantage of the MemoryMappedViewAccessor class. It still uses marshaling, it is hidden under the floor mat.

Hans Passant
I will look into MemoryMappedViewAccessor as soon as new framework will be officialy released, thank you
marco.ragogna