有没有办法将结构转换为字节数组?

时间:2014-05-21 06:56:57

标签: vb.net

我有一个带有明确定义的字段偏移的vb.net pod结构。在这种情况下,它应该准备好立即从内存复制到一堆字节。虽然我还没有找到任何方法这样做..提示?

1 个答案:

答案 0 :(得分:2)

单程
序列化对象(取自:Convert structure to byte array in .NET

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

有关详细信息,请参阅链接的SO文章。

第二种方式
使用System.Runtime.InteropServices命名空间中的Marshal类和GCHandle结构:

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

托管对象需要GCHandle。在这里,它基本上精确定位结构的内存地址并将其保存在ptr变量中。然后,您可以找到结构的大小,并将字节读入结果数组res