Structure to ByteArray Problems

  • Thread starter Thread starter BigC
  • Start date Start date
B

BigC

Hi,

I am having problems converting from a Structure to a ByteArray. The
main problem being that the structure contains a variable length array,
which cannot be defined within the structure definition. A example of
my code is shown below and when this is run, an error is produced
within the BuildByteArray function due to the structure size not being
set.

Any help would be greatly appreciated.

CODE
----

Public g_by2DOpBuffer(1023) As Byte
Public Structure Struct1
Public Field1 As Integer
Public Array1() As Integer
End Structure


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

Dim message As New Struct1()

message.Array1 = 2
Redim message.Array1(message.Field1)
BuildByteArray(message, g_by2DOpBuffer)

End Sub

Public Function BuildByteArray(ByVal UserData As Object, ByVal
ByteArray() As Byte) As Byte()

Dim Ptr As IntPtr =
Marshal.AllocHGlobal(Marshal.SizeOf(UserData))

'now copy strcutre to Ptr pointer
Marshal.StructureToPtr(UserData, Ptr, False)
Marshal.Copy(Ptr, ByteArray, 0, Marshal.SizeOf(UserData))

Marshal.FreeHGlobal(Ptr)

End Function
 
I am having problems converting from a Structure to a ByteArray. The
main problem being that the structure contains a variable length array,
which cannot be defined within the structure definition. A example of
my code is shown below and when this is run, an error is produced
within the BuildByteArray function due to the structure size not being
set.

Wouldn't it be easier to forget about the structure and just use a
BinaryWriter on top of a MemoryStream?



Mattias
 
I have no knowledge/experience of using BinaryWriter or MemoryStream
but it may be an option. Would it be an easy job to replace the
structures ? An example would help. The reason I ask is that I have
over 50 structures within my code which are used extensively.
 
Back
Top