O
O.B.
In the following example, the MyStructure constructor takes an array
of 8 bytes. I was hoping that PtrToStructure would copy only the
first 8 bytes. But for some reason, it is also instantiating Records
with an array of length 1 and putting random values in it. I desire
for this array to remain null if there is no memory to marshal to it.
What am I doing wrong?
using System;
using System.Runtime.InteropServices;
namespace MarshallingTest
{
public class Program
{
public struct Human
{
public int NumLegs;
public int NumArms;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class MyStructure
{
public int Padding;
public uint NumRecords;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType =
UnmanagedType.Struct)]
public Human[] Records;
public MyStructure(byte[] rawData)
{
unsafe
{
fixed (byte* pData = rawData)
{
Marshal.PtrToStructure((IntPtr)pData, this);
}
}
}
}
public Program()
{
byte[] testData = new byte[8];
MyStructure test = new MyStructure(testData);
// I'm expecting test.Records to be null. Why is it
instantiated
// with a size of 1?
Console.WriteLine("Number of Records = " +
test.Records.Length);
}
public static void Main(string[] args)
{
new Program();
}
}
}
of 8 bytes. I was hoping that PtrToStructure would copy only the
first 8 bytes. But for some reason, it is also instantiating Records
with an array of length 1 and putting random values in it. I desire
for this array to remain null if there is no memory to marshal to it.
What am I doing wrong?
using System;
using System.Runtime.InteropServices;
namespace MarshallingTest
{
public class Program
{
public struct Human
{
public int NumLegs;
public int NumArms;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class MyStructure
{
public int Padding;
public uint NumRecords;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType =
UnmanagedType.Struct)]
public Human[] Records;
public MyStructure(byte[] rawData)
{
unsafe
{
fixed (byte* pData = rawData)
{
Marshal.PtrToStructure((IntPtr)pData, this);
}
}
}
}
public Program()
{
byte[] testData = new byte[8];
MyStructure test = new MyStructure(testData);
// I'm expecting test.Records to be null. Why is it
instantiated
// with a size of 1?
Console.WriteLine("Number of Records = " +
test.Records.Length);
}
public static void Main(string[] args)
{
new Program();
}
}
}