//結構體的定義
[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"
}
/**************************************************/