You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中结构转Byte Array时Byte成员占4字节、结构大小异常问题

问题原因:结构内存对齐机制

你遇到的大小差异是.NET默认的**结构字节对齐(内存对齐)**规则导致的,这是运行时为了提升内存访问效率做的默认优化:

  • .NET默认封送结构时,对齐粒度取结构中最大的非引用类型成员的大小,你这个结构里Integer、Single都是4字节,所以默认对齐粒度为4字节。
  • 每个成员的起始内存偏移必须是自身类型大小的整数倍:你定义的RotationDirection是Byte类型,仅占1字节,它后面紧跟着的ID_1是4字节的Integer类型,必须从4的整数倍偏移位置开始存储,所以RotationDirection后面会自动补3个字节的填充位(padding),这3个字节没有实际数据,只是用来占位对齐。
  • 总大小计算:你手动统计的成员总大小是61字节,加上3字节的填充位,总大小刚好是64字节,和你测试的结果一致;去掉RotationDirection后没有需要对齐的偏移,自然就少了4字节(1字节数据+3字节填充)。

解决方案:强制1字节对齐

如果你需要结构按实际成员大小紧凑排列,不填充对齐位,可以给结构加上StructLayout特性,指定封装大小为1:

Imports System.Runtime.InteropServices

<StructLayout(LayoutKind.Sequential, Pack:=1)>
Public Structure SendDriveParams
        Public Command_code As Integer
        Public Drive_source As Integer
        Public Duration As Single
        Public RotationDirection  As Byte
        Public ID_1 As Integer
        Public Value_1 As Single
        Public ID_2 As Integer
        Public Value_2 As Single
        Public ID_3 As Integer
        Public Value_3 As Single
        Public ID_4 As Integer
        Public Value_4 As Single
        Public ID_5 As Integer
        Public Value_5 As Single
        Public ID_6 As Integer
        Public Value_6 As Single
End Structure

设置后再用Marshal.SizeOf计算得到的结构大小就是61字节,和你手动计算的一致。


内容的提问来源于stack exchange,提问作者Werner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 14:54:03