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)


- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01