Structure to ByteArray Problems

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
 
M

Mattias Sjögren

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
 
B

BigC

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top