When marshaling an instance of a class type, the type needs a constructor without parameters. Otherwise Marshal.PtrToStructure MissingMethodException. When sorting an instance that contains nested classes, they don't need a constructor without parameters.
See the sample code below. Marshalling works correctly, output 1 2 3 4. But why DummyNesteddoesn't the class need a constructor without parameters?
static void Main(string[] args)
{
var buffer = new byte[10];
buffer[0] = 1;
buffer[1] = 2;
buffer[2] = 3;
buffer[3] = 4;
Dummy dummy;
unsafe
{
fixed(byte* bufferPtr = &buffer[0])
{
dummy = (Dummy)Marshal.PtrToStructure(new IntPtr(bufferPtr), typeof(Dummy));
}
}
Console.WriteLine("{0} {1} {2} {3}", dummy.m_nested1.m_data1, dummy.m_nested1.m_data2, dummy.m_nested2.m_data1, dummy.m_nested2.m_data2);
Console.ReadKey();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private class DummyNested
{
public byte m_data1;
public byte m_data2;
public DummyNested(byte data1, byte data2)
{
m_data1 = data1;
m_data2 = data2;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private class Dummy
{
public DummyNested m_nested1;
public DummyNested m_nested2;
private Dummy()
{
}
public Dummy(DummyNested n1, DummyNested n2)
{
m_nested1 = n1;
m_nested2 = n2;
}
}
source
share