ExtensionMethod.NET Home of 844 C#, Visual Basic, F# and Javascript extension methods


Converts Structure To Byte-Array and back


Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices

Module StructureExtensions

    ''' <summary>
    ''' Converts simple structure to byte-array
    ''' </summary>
    ''' <typeparam name="T"></typeparam>
    ''' <param name="[structure]"></param>
    ''' <returns></returns>
    Public Function ToByteArray(Of T As Structure)(ByVal [structure] As T) As Byte()
        Dim bufferSize = Marshal.SizeOf([structure])
        Dim byteArray = New Byte(bufferSize - 1) {}
        Dim handle As IntPtr = Marshal.AllocHGlobal(bufferSize)
            Marshal.StructureToPtr([structure], handle, False)
            Marshal.Copy(handle, byteArray, 0, bufferSize)
        End Try

        Return byteArray
    End Function

    ''' <summary>
    ''' converts byte-array to simple structure
    ''' </summary>
    ''' <typeparam name="T"></typeparam>
    ''' <param name="bytearray"></param>
    ''' <returns></returns>
    Public Function ToStructure(Of T As Structure)(ByVal bytearray As Byte()) As T
        Dim [structure] As New T
        Dim len As Integer = Marshal.SizeOf([structure])
        Dim i As IntPtr = Marshal.AllocHGlobal(len)
        Marshal.Copy(bytearray, 0, i, len)
        [structure] = Marshal.PtrToStructure(i, [structure].[GetType]())
        Return [structure]
    End Function

End Module


Public Structure TestStruct
    Dim x64 As Int64
    Dim str As String
    Dim truth As Boolean
    Dim x16 As Int16
End Structure

Dim tstrct As New TestStruct
tstrct.x64 = Int64.MaxValue
tstrct.truth = True
tstrct.str = "hello struct"
tstrct.x16 = 5

Dim fooba = tstrct.ToByteArray
Dim barstrct = fooba.ToStructure(Of TestStruct)
Dim yeah = barstrct.Equals(tstrct)

Author: Mike Lorenz

Submitted on: 17 apr 2018

Language: VB

Type: Structure

Views: 2923