Created
July 25, 2017 01:38
-
-
Save 303248153/76463fa4ef5e2111828aedf83e02de6c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static uint SizeOf(object obj) | |
{ | |
unsafe | |
{ | |
var objRef = __makeref(obj); | |
var objPtr = **(IntPtr**)(&objRef); | |
var mtPtr = *((IntPtr*)objPtr); | |
var componentSize = *((ushort*)(mtPtr + 0)); | |
var flags = *((ushort*)(mtPtr + 2)); | |
var baseSize = *((uint*)(mtPtr + 4)); | |
// array, check enum_flag_HasComponentSize | |
if ((flags & 0x8000) != 0) | |
{ | |
var length = *(int*)(objPtr + sizeof(IntPtr)); | |
return (uint)(componentSize * length); | |
} | |
// value type, check enum_flag_Category_ValueType | |
if ((flags & 4) != 0) | |
{ | |
var arr = Expression.Lambda<Func<object>>( | |
Expression.NewArrayBounds(obj.GetType(), Expression.Constant(1))).Compile()(); | |
return SizeOf(arr); | |
} | |
return baseSize; | |
} | |
} | |
static void Main(string[] args) | |
{ | |
Console.WriteLine(SizeOf(1)); | |
Console.WriteLine(SizeOf(1L)); | |
Console.WriteLine(SizeOf(new ClassA())); | |
Console.WriteLine(SizeOf(new ClassB())); | |
Console.WriteLine(SizeOf(new int[100])); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment