【问题标题】:Why cant i declare a fixed array as an overlapping member in a structure?为什么我不能将固定数组声明为结构中的重叠成员?
【发布时间】:2014-07-16 15:34:34
【问题描述】:

这是一个示例:

Imports System.Runtime.InteropServices

<StructLayout(LayoutKind.Explicit)>
Public Structure TimeStamp32
    <FieldOffset(0)>
    Public I32 As Int32
    <FieldOffset(0)>
    <VBFixedArray(3)> Public Bytes() As Byte
End Structure

它给了我一个错误提示“无法加载类型 TimeStamp32 ..blah blah.. 因为它包含偏移 0 处的对象字段,该对象字段未正确对齐或被非对象字段重叠。”虽然我可以将 int 与单个或任何其他 4 字节变量重叠没问题。

我实际上并不需要这个结构,但如果有办法让它工作,它将极大地帮助我管理我的 128 位 ID 结构和可能的其他结构。

【问题讨论】:

标签: vb.net


【解决方案1】:

我已将此标记为重复,但我将分享一个“解决方法”。

<StructLayout(LayoutKind.Explicit)>
Public Structure TimeStamp32

    <FieldOffset(0)> Public Value As Integer
    <FieldOffset(0)> Public Byte1 As Byte
    <FieldOffset(1)> Public Byte2 As Byte
    <FieldOffset(2)> Public Byte3 As Byte
    <FieldOffset(3)> Public Byte4 As Byte

    Public Sub New(value As Integer)
        Me.Value = value
    End Sub

    Public Sub New(byte1 As Byte, byte2 As Byte, byte3 As Byte, byte4 As Byte)
        Me.Byte1 = byte1
        Me.Byte2 = byte2
        Me.Byte3 = byte3
        Me.Byte4 = byte4
    End Sub

    Public ReadOnly Property Bytes() As Byte()
        Get
            Return New Byte() {Me.Byte1, Me.Byte2, Me.Byte3, Me.Byte4}
        End Get
    End Property

End Structure

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多