当结构包含字节变量时,如何避免多余的字节?(VB.NET)

How to avoid an excess byte when a structure contains a byte variable? (VB.NET)(当结构包含字节变量时,如何避免多余的字节?(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.AllocHGlobalMarshal.StructureToPtrMarshal.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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)