I want to pin some managed object in .Net for coping it data into byte array. For pinning and coping I use next code:
C c = new C();
byte[] b = new byte[Marshal.SizeOf(c)];
GCHandle gch = GCHandle.Alloc(c, GCHandleType.Pinned);
Marshal.Copy(gch.AddrOfPinnedObject(), b, 0, b.Length);
gch.Free();
And when I declare my object definitions as folow:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct A
{
public int a;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct C
{
public A a0;
public A a1;
public A a2;
}
All work fine. When I declare my object definitions as folow:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct A
{
public int a;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
class C
{
public A a0;
public A a1;
public A a2;
}
Also all work fine. But when I declare both my objects as class:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
class A
{
public int a;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
class C
{
public A a0;
public A a1;
public A a2;
}
then ArgumentException is thrown in GCHandle.Alloc(...) 'Object contains non-primitive or non-blittable data.'
Why when A is defined as struct all work fine. But when as class is not work? It is possible to make this work with both types A and C defined as classes?