VB.NET用Marshal.PtrToStructure 方法实现数据在数组和结构间复制

来源:互联网 发布:手机字体美化软件 编辑:程序博客网 时间:2024/06/06 12:08
Imports SystemImports System.Runtime.InteropServicesPublic Structure Point    Public x As Integer    Public y As IntegerEnd StructureModule Example    Sub Main()        ' Create a point struct.        Dim p As Point        p.x = 1        p.y = 1        Console.WriteLine("The value of first point is " + p.x.ToString + " and " + p.y.ToString + ".")        ' Initialize unmanged memory to hold the struct.        Dim pnt As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(p))        Try            ' Copy the struct to unmanaged memory.            Marshal.StructureToPtr(p, pnt, False)            ' Create another point.            Dim anotherP As Point            ' Set this Point to the value of the             ' Point in unmanaged memory.             anotherP = CType(Marshal.PtrToStructure(pnt, GetType(Point)), Point)            Console.WriteLine("The value of new point is " + anotherP.x.ToString + " and " + anotherP.y.ToString + ".")        Finally            ' Free the unmanaged memory.            Marshal.FreeHGlobal(pnt)        End Try    End SubEnd Module
原创粉丝点击