如何获取结构成员的相对字节位置 [英] how to get the relative byte position of a structure member

查看:96
本文介绍了如何获取结构成员的相对字节位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,



我想在一个更大的结构中找出结构成员的地址/字节位置

。下面是一个非常简单的例子,我的结构要复杂得多,并且不仅包含字节值,如下所示。它们也包括数组,int16值等。那么,我如何获得的相对地址,例如预设字节,或Range_B.b01 ...值,与结构起始地址相关



谢谢



例如:

Hello out there,

I like to find out the address/ byte position of a structure member
within a bigger structure. Below a very simple example, my structure is much more complicated, and containes not only bytes value, like below. Their are also arrays included, int16 values and so on. So, how can I get the relative address of e.g. the "Preset" Byte, or "Range_B.b01..." Value, in relation to the structure start address.

Thanks

example:

<Serializable()> _
<StructLayout(LayoutKind.Sequential, Pack:=1)> _
Public Structure sConfig
    <MarshalAs(UnmanagedType.U1)> _
    Dim Id As Byte

    Dim Range_V As sRange
    Dim Range_B As sRange

    <MarshalAs(UnmanagedType.U1)> _
    Dim Preset As Byte

    Dim Version As sVersion
End Structure

<Serializable()> _
<StructLayout(LayoutKind.Sequential, Pack:=1)> _
Public Structure sapRange
    <MarshalAs(UnmanagedType.U1)> _
    Dim b00_Range_Minimum As Byte

    <MarshalAs(UnmanagedType.U1)> _
    Dim b01_Range_Default As Byte

    <MarshalAs(UnmanagedType.U1)> _
    Dim b02_Range_Maximum As Byte
End Structure

<Serializable()> _
<StructLayout(LayoutKind.Sequential, Pack:=1)> _
Public Structure sVersion
    <MarshalAs(UnmanagedType.U1)> _
    Public Hbyte As Byte

    <MarshalAs(UnmanagedType.U1)> _
    Public Lbyte As Byte
End Structure


sub getBytePos

        Dim theStruct as sConfig

        Dim ptrStartAddress As New IntPtr(theStruct.Id)
        Dim ptr As New IntPtr(theStruct.Preset)

        Dim deltaByteCount As Integer
        deltaByteCount = ptr - ptrStartAddress
        '# ==> this does not give the right result

end sub

推荐答案

参见 Marshal.OffsetOf方法 [ ^ ]


大家好,



感谢您的回复。



解决方案如下,只有一个入口点

,我现在必须做进一步的编码。



谢谢



Hi all,

and thanks for the response.

The solution is as follows, and only a entry point
for further coding I have to do now.

Thanks

Dim instance as sConfig

Dim fName as String
    fName = "Preset"

Dim byteOffset As Integer
    byteOffset = Marshal.OffsetOf(instance.GetType, fName)

Debug.Print("byteOffset: " & byteOffset)


=> byteOffset: 7


这篇关于如何获取结构成员的相对字节位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆