2

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 Answers 2

5

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.

1
  • I will look into MemoryMappedViewAccessor as soon as new framework will be officialy released, thank you
    – Drake
    Apr 7, 2010 at 16:15
1

Bitconverter.GetBytes((dynamic)v);

1
  • 1
    Welcome to Stack Overflow. Code-only answers are discouraged because they do not explain how they resolve the issue in the question. Consider updating your answer to explain what this does and how it addresses the problem so that is will be helpful to others with similar issues in future. Please review How do I write a good answer Sep 23, 2017 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.