Get size of struct in C# [duplicate]
Possible Duplicate:
How to check the number of bytes consumed by my Structure?
I have a struct in the packed form of
[StructLayout(LayoutK开发者_Go百科ind.Sequential, Pack = 1)]
public struct test
{
public int a;
public uint16 b;
}
How do I get the size of the struct as the compiler states that sizeof can only be used in unsafe context?
The SizeOf
method does the trick.
int size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(Point));
You put the sizeof operator into an unsafe context just like the compiler suggests?
Something like this I guess:
int size;
unsafe
{
size=sizeof(Test);
}
But I'm not sure if you really want to do that. I'd tend to use a normal serializer instead of structs with specific layout for this. IMO you should use such structs only for native interop and not for simple serialization.
And looking at the documentation of the SizeOf
function marshalling can mess with the size too(not in this example though).
精彩评论