//结构体的定义
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct VGAStat
{
public int length;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public int[] number;
}
public struct VGAStat1
{
public string str;
public IntPtr intptr1;//指针的定义
}
private void Form1_Load(object sender, EventArgs e)
{
/********初始化结构体VGAStat*****************/
VGAStat pp = new VGAStat();
pp.length = 123;
pp.number=new int[6];
for (int i = 0; i < 6; i++)
{
pp.number[i] = i + 1;
}
/**************************************************/
IntPtr intpt = Marshal.AllocHGlobal(Marshal.SizeOf(pp)); //对intpt分配内存
Marshal.StructureToPtr(pp, intpt, true); 将数据封送到intpt
/********初始化结构体VGAStat1*****************/
VGAStat1 vga = new VGAStat1();
vga.intptr1 = intpt;
/**************************************************/
VGAStat entries = (VGAStat)Marshal.PtrToStructure(vga.intptr1, typeof(VGAStat));
/********读取结构体数据*****************/
string Number = string.Empty;
int ReadLength = entries.length; //ReadLength=132
for (int i = 0; i < 6; i++)
{
Number = Number + entries.number[i].ToString(); //Number="123456"
}
/**************************************************/