J
Jon Jagger
I was thinking about how you can only use sizeof to find the size of an
unmanaged type. I started to wonder if there was a way to find the size of a
managed object and came up with the following. It's not guaranteed behaviour
but it seems to work. Doesn't lose verifiability either. Enjoy.
Cheers
Jon Jagger
namespace JSL
{
using System.Runtime.InteropServices;
public delegate object Creator();
public static class Size
{
public static int Of(Creator f)
{
Union a = new Union();
a.u2.o = f();
Union b = new Union();
b.u2.o = f();
return System.Math.Abs(a.u1.value - b.u1.value);
}
private struct U1
{
public int value;
}
private struct U2
{
public object o;
}
[StructLayout(LayoutKind.Explicit)]
private struct Union
{
[FieldOffset(0)] public U1 u1;
[FieldOffset(0)] public U2 u2;
}
}
}
namespace Example
{
using JSL;
using System;
class C
{
public C()
{
a = b = c = d = 42;
}
private int a,b,c,d;
}
class App
{
static void Main()
{
Creator c = delegate { return new C(); };
Console.WriteLine(Size.Of(c));
}
}
}
unmanaged type. I started to wonder if there was a way to find the size of a
managed object and came up with the following. It's not guaranteed behaviour
but it seems to work. Doesn't lose verifiability either. Enjoy.
Cheers
Jon Jagger
namespace JSL
{
using System.Runtime.InteropServices;
public delegate object Creator();
public static class Size
{
public static int Of(Creator f)
{
Union a = new Union();
a.u2.o = f();
Union b = new Union();
b.u2.o = f();
return System.Math.Abs(a.u1.value - b.u1.value);
}
private struct U1
{
public int value;
}
private struct U2
{
public object o;
}
[StructLayout(LayoutKind.Explicit)]
private struct Union
{
[FieldOffset(0)] public U1 u1;
[FieldOffset(0)] public U2 u2;
}
}
}
namespace Example
{
using JSL;
using System;
class C
{
public C()
{
a = b = c = d = 42;
}
private int a,b,c,d;
}
class App
{
static void Main()
{
Creator c = delegate { return new C(); };
Console.WriteLine(Size.Of(c));
}
}
}