1

I have a vb.net pod structure with explicitly defined field offsets. In such case, it should be ready to immediately copy from memory to whatever as a bunch of bytes. All though i haven't found any way to do that.. tips?

Jake Freelander
  • 1,471
  • 1
  • 19
  • 26

1 Answers1

2

One way
Serialize the object (taken from: Convert structure to byte array in .NET )

Dim formatter As New BinaryFormatter
formatter.Serialize(outputFileStream, objectInstance)

See the linked SO-article for details.

Second way
Use the Marshal Class and the GCHandle structure in the System.Runtime.InteropServices namespace:

Dim myStrct As New strFoo 'The object of the structure
Dim ptr As IntPtr 'Will contain the memory address of the structure
Dim gc As System.Runtime.InteropServices.GCHandle = System.Runtime.InteropServices.GCHandle.Alloc(myStrct, Runtime.InteropServices.GCHandleType.Pinned) 'Used to find said address
ptr = gc.AddrOfPinnedObject 'Save address in pointer variable
Dim strcLength As Integer = System.Runtime.InteropServices.Marshal.SizeOf(myStrct) 'Find the size of the structure. Should be a sequential structure.
Dim res(strcLength - 1) As Byte 'Will contain the bytes you want
For i = 0 To strcLength - 1
    res(i) = System.Runtime.InteropServices.Marshal.ReadByte(ptr, i) 'Read bytes one by one.
Next
gc.Free() 'Release the GCHandle

The GCHandle is needed for managed objects. Here it basically pinpoints the memory address of the structure and saves it in the ptr variable. You then find the size of the structure and read the bytes into the result array res.

Community
  • 1
  • 1
Jens
  • 6,275
  • 2
  • 25
  • 51