在解析C#結構體指針前,必須知道C#結構體是如何定義的。在c#中同樣定義該結構體。
C#結構體指針之C#結構體的定義:
[StructLayout(LayoutKind.Sequential)] public struct VGAStat { public int ChannelNum;//通道數量 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] public char[] Version;//版本信息 public uint CPUUsage;//CPU占用 public bool WorkStatusOk; //工作狀態 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public tagCheckArg[] ChannelStatistic;//通道信息 }
定義完結構體后,就可將接收到的C#結構體指針轉換為定義的結構體對象。
VGAStat entries = (VGAStat)Marshal.PtrToStructure(iptr, typeof(VGAStat)); //iptr為接收到的非托管的結構體指針。
反之,也可將結構體賦值后封送到非托管內存。
假如vga為定義后實例化並賦值了的結構體。
IntPtr intptr = Marshal.AllocHGlobal(Marshal.SizeOf(vga)); Marshal.StructureToPtr(vga, intptr, true); //在此發送intptr指針給目的方 Marshal.FreeHGlobal(intptr);//釋放分配的非托管內存。
C#結構體指針的定義及使用的相關內容那個就向你介紹到這里,希望對你了解和學習C#結構體指針有所幫助。
轉載自:http://developer.51cto.com/art/200908/143813.htm