如何将自定义的structure转换为byte数组

skyspeed 2005-09-20 04:20:56
我自定义的一个structure,因为要用网络传输,想将该类型的变量转换成byte数组,或者将该structure的内容copy到一个byte数组里也可以,该如何做呢?

刚用VB,感觉很不习惯,在C/C++里就一句话的事啊。 我用的VB.net,希望能指点一下

...全文
247 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
是是非非 2005-09-21
  • 打赏
  • 举报
回复
VB 里面可以 LSet
VB.Net就没用过了~
zlt982001 2005-09-21
  • 打赏
  • 举报
回复

Dim myStru As aa
myStru.a1 = "AA"
myStru.a2 = 1
myStru.a3 = 2


Dim rawsize As Integer = Runtime.InteropServices.Marshal.SizeOf(myStru)
Dim buffer As IntPtr = Runtime.InteropServices.Marshal.AllocHGlobal(rawsize)

Runtime.InteropServices.Marshal.StructureToPtr(myStru, buffer, False)

Dim rawdatas(rawsize - 1) As Byte

Runtime.InteropServices.Marshal.Copy(buffer, rawdatas, 0, rawsize)
Runtime.InteropServices.Marshal.FreeHGlobal(buffer)



MsgBox(UBound(rawdatas))
'rawdatas 就是你需要的Byte()
skyspeed 2005-09-21
  • 打赏
  • 举报
回复
没人碰到过这个问题吗?如果用到VB.net网络编程,应该都会有这样的问题吧
zlt982001 2005-09-21
  • 打赏
  • 举报
回复
郁闷,我的回答只值5分,唉
skyspeed 2005-09-21
  • 打赏
  • 举报
回复
hi, northwolves, thanks for your solution:

You could convert each struct field to a byte-array, e.g. BitConverter.GetBytes(.) or
ASCIIEncoding.GetBytes( String )

and concatenate the byte-arrays e.g. with Array.Copy()


I have tried to find the same solution, and your suggestion verified my method.
northwolves 2005-09-21
  • 打赏
  • 举报
回复
http://www.dotnet247.com/247reference/msgs/2/12080.aspx
skyspeed 2005-09-20
  • 打赏
  • 举报
回复
是vb.net
zlt982001 2005-09-20
  • 打赏
  • 举报
回复
是.net 还是 VB6
skyspeed 2005-09-20
  • 打赏
  • 举报
回复
ASPI的copymemory?麻烦问一下具体如何调用,谢谢!高分相送
TechnoFantasy 2005-09-20
  • 打赏
  • 举报
回复
可以用ASPI函数copymemory实现。

7,759

社区成员

发帖
与我相关
我的任务
社区描述
VB 基础类
社区管理员
  • VB基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧