Hola, aca un ejemplo de VB .NET para hacer eso, hay mucha info en internet de esto igual, mucho para C#.
Imports System
Imports System.Runtime.InteropServices
Public Class Form1
<StructLayout(LayoutKind.Sequential, Pack:=1)> _
Private Structure MyStruct
Public id As Integer
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=20)> _
Public text As String
End Structure
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Llenamos la estructura con algunos datos
Dim msg As MyStruct
msg.id = 888
msg.text = "Holaaaaaa1"
'La convertimos a Bytes
Dim bytes As Byte() = StructToByteArray(msg)
'Convertimos el array de bytes a la estructura nuevamente
Dim msg2 As MyStruct = ByteArrayToStruct(bytes)
MsgBox(msg2.id)
MsgBox(msg2.text)
End Sub
Private Function ByteArrayToStruct(ByVal bytes As Byte()) As MyStruct
Dim handle As GCHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned)
Dim stuff As MyStruct = DirectCast(Marshal.PtrToStructure(handle.AddrOfPinnedObject(), GetType(MyStruct)), MyStruct)
handle.Free()
Return stuff
End Function
Private Function StructToByteArray(ByVal logFont As MyStruct) As Byte()
Dim length As Integer = Marshal.SizeOf(logFont)
Dim ptPoint As IntPtr = Marshal.AllocHGlobal(length)
Marshal.StructureToPtr(logFont, ptPoint, True)
Dim bff As Byte() = New Byte(length - 1) {}
Marshal.Copy(ptPoint, bff, 0, length)
Marshal.FreeHGlobal(ptPoint)
Return bff
End Function
End Class