有没有办法将结构转换为字节数组? [英] Is there a way to convert a structure to a byte array?

查看:43
本文介绍了有没有办法将结构转换为字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

一种方式
序列化对象(取自:将结构转换为 .网络 )

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

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

See the linked SO-article for details.

第二种方式
使用 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.

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.

这篇关于有没有办法将结构转换为字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆