How to avoid an excess byte when a structure contains a byte variable? (VB.NET)(当结构包含字节变量时,如何避免多余的字节?(VB.NET))
问题描述
VB.NET 4.5
我定义了一个只包含一个字节的结构。我需要获取要通过串口发送的字节数组。
Public Structure ExampleStructure
Public variable1 As Byte
Public variable2 As UInt16
Public variable3 As UInt16
Public Function getBytes() As Byte()
Dim binaryBytes(5) As Byte
Dim pointerCommand As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(Me))
Marshal.StructureToPtr(Me, pointerCommand, False)
Marshal.Copy(pointerCommand, binaryBytes, 0, Marshal.SizeOf(Me))
Marshal.FreeHGlobal(pointerCommand)
Return binaryBytes
End Function
End Structure
问题是:
当我使用Marshal.AllocHGlobal、Marshal.StructureToPtr和Marshal.Copy时,返回的字节数组为6字节。.NET为Variable1创建了2个字节,因此在Variable1和Variable2数据之间有多余的字节。
我可以通过使用LayoutKind.Explicit并定义FieldOffsets来解决此问题。
<StructLayout(LayoutKind.Explicit)> _
Public Structure ExampleStructure
<FieldOffset(0)> Public variable1 As Byte
<FieldOffset(1)> Public variable2 As UInt16
<FieldOffset(3)> Public variable3 As UInt16
Public Function getBytes() As Byte()
Dim binaryBytes(5) As Byte
Dim pointerCommand As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(Me))
Marshal.StructureToPtr(Me, pointerCommand, False)
Marshal.Copy(pointerCommand, binaryBytes, 0, Marshal.SizeOf(Me))
Marshal.FreeHGlobal(pointerCommand)
Return binaryBytes
End Function
End Structure
现在,当我获取字节数时,varable1和varable2之间不再有多余的字节。
尽管这似乎是一种笨拙的方式。有没有更好的选择,让我不必手动设置FieldOffsets?这个结构很简单,但它们可能会变得复杂得多。
推荐答案
修复非常简单-只需添加标记LayoutKind.Sequential,Pack:=1
<StructLayout(LayoutKind.Sequential, Pack:=1)> _
Public Structure ExampleStructure
Public variable1 As Byte
Public variable2 As UInt16
Public variable3 As UInt16
Public Function getBytes() As Byte()
Dim binaryBytes(5) As Byte
Dim pointerCommand As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(Me))
Marshal.StructureToPtr(Me, pointerCommand, False)
Marshal.Copy(pointerCommand, binaryBytes, 0, Marshal.SizeOf(Me))
Marshal.FreeHGlobal(pointerCommand)
Return binaryBytes
End Function
End Structure
这篇关于当结构包含字节变量时,如何避免多余的字节?(VB.NET)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当结构包含字节变量时,如何避免多余的字节?(VB.NET)
基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
