在VB.NET中,可以使用Marshal類的PtrToStructure方法和StructureToPtr方法來實現結構體和字節數組之間的相互轉換。
以下是一個示例代碼:
```vb
Imports System.Runtime.InteropServices
Public Structure MyStruct
Public Field1 As Integer
Public Field2 As Double
End Structure
Public Class Program
Public Shared Sub Main()
' 創建一個結構體實例
Dim myStruct As New MyStruct()
myStruct.Field1 = 10
myStruct.Field2 = 3.14
' 將結構體轉換為字節數組
Dim byteSize As Integer = Marshal.SizeOf(myStruct)
Dim byteArray(byteSize - 1) As Byte
Dim structPtr As IntPtr = Marshal.AllocHGlobal(byteSize)
Marshal.StructureToPtr(myStruct, structPtr, False)
Marshal.Copy(structPtr, byteArray, 0, byteSize)
Marshal.FreeHGlobal(structPtr)
' 將字節數組轉換回結構體
Dim newStruct As MyStruct = New MyStruct()
structPtr = Marshal.AllocHGlobal(byteSize)
Marshal.Copy(byteArray, 0, structPtr, byteSize)
newStruct = Marshal.PtrToStructure(structPtr, GetType(MyStruct))
Marshal.FreeHGlobal(structPtr)
' 輸出轉換后的結構體字段值
Console.WriteLine("Field1: " & newStruct.Field1)
Console.WriteLine("Field2: " & newStruct.Field2)
End Sub
End Class
```
運行以上代碼,將會輸出:
```
Field1: 10
Field2: 3.14
```
這樣就實現了結構體和字節數組之間的相互轉換。