天天看點

[VB.Net]擷取對象的指針及結構體與位元組數組間的互相轉化

參考網上的方法,使用了GCHandle,http://blog.csdn.net/gxwxca/archive/2007/04/26/1585496.aspx,他的文章寫得有點複雜,其實就是下面的兩行

Dim GCH As GCHandle = GCHandle.Alloc(對象, GCHandleType.Pinned)

Dim tPtr As IntPtr = GCH.AddrOfPinnedObject

另外附上結構體與位元組數組間互相轉化的代碼

''' <summary>

''' 結構體轉換成位元組數組

''' </summary>

''' <param name="oStructure">要轉化的結構體</param>

Public Shared Function StructureToByteArray(ByVal oStructure As Object) As Byte()

Dim oSize As Integer = Marshal.SizeOf(oStructure)

Dim tByte(oSize - 1) As Byte

Dim tPtr As IntPtr = Marshal.AllocHGlobal(oSize)

Marshal.StructureToPtr(oStructure, tPtr, False)

Marshal.Copy(tPtr, tByte, 0, oSize)

Marshal.FreeHGlobal(tPtr)

Return tByte

End Function

''' <summary>

''' 位元組數組轉換成結構體

''' </summary>

''' <param name="arrByte">要轉化的位元組數組</param>

''' <param name="oType">要轉化成的結構體類型</param>

Public Shared Function ByteArrayToStructure(ByVal arrByte() As Byte, ByVal oType As Type) As Object

Dim oSize As Integer = Marshal.SizeOf(oType)

If oSize > arrByte.Length Then Return Nothing

Dim tPtr As IntPtr = Marshal.AllocHGlobal(oSize)

Marshal.Copy(arrByte, 0, tPtr, oSize)

Dim oStructure As Object = Marshal.PtrToStructure(tPtr, oType)

Marshal.FreeHGlobal(tPtr)

Return oStructure

End Function