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

Imports System
Imports System.Runtime.InteropServices



Public Structure Point
    Public x As Integer
    Public y As Integer
End Structure


Module 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 Sub
End Module
VB.NET 环境中,`Marshal` 是一个用于进行互操作操作的类。它提供了一些方法和属性,用于在托管代码和非托管代码之进行数据转换、内存分配和释放等操作。 下面是 `Marshal` 类的常用成员和使用方法: 1. `AllocCoTaskMem(size As Integer)`:分配指定大小的内存块,并返回指向该内存块的指针。 ```vb Dim ptr As IntPtr = Marshal.AllocCoTaskMem(100) ``` 2. `FreeCoTaskMem(ptr As IntPtr)`:释放由 `AllocCoTaskMem` 分配的内存块。 ```vb Marshal.FreeCoTaskMem(ptr) ``` 3. `Copy(source As Byte(), startIndex As Integer, destination As IntPtr, length As Integer)`:将字节数组的一部分复制到指定内存地址。 ```vb Dim data As Byte() = {1, 2, 3, 4, 5} Dim ptr As IntPtr = Marshal.AllocCoTaskMem(data.Length) Marshal.Copy(data, 0, ptr, data.Length) ``` 4. `StructureToPtr(structure As Object, ptr As IntPtr, fDeleteOld As Boolean)`:将结构体转换为指向非托管内存的指针。 ```vb Dim obj As MyStruct Dim ptr As IntPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(obj)) Marshal.StructureToPtr(obj, ptr, False) ``` 5. `PtrToStructure(ptr As IntPtr, structureType As Type)`:将指向非托管内存的指针转换为结构体。 ```vb Dim obj As MyStruct = Marshal.PtrToStructure(ptr, GetType(MyStruct)) ``` 6. `StringToHGlobalAnsi(s As String)`:将 ANSI 编码的字符串分配到非托管内存,并返回指向该内存的指针。 ```vb Dim str As String = "Hello" Dim ptr As IntPtr = Marshal.StringToHGlobalAnsi(str) ``` 7. `FreeHGlobal(ptr As IntPtr)`:释放由 `StringToHGlobalAnsi` 分配的内存。 ```vb Marshal.FreeHGlobal(ptr) ``` 这些是 `Marshal` 类的一些常用方法,可以根据需要选择合适的方法来进行数据转换、内存操作等操作。需要注意的是,在使用 `Marshal` 类时,需要引入 `System.Runtime.InteropServices` 命名空
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值