标题:数组转结构体问题
只看楼主
linlvbin
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2010-11-29
结帖率:33.33%
已结贴  问题点数:20 回复次数:2 
数组转结构体问题
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
        public struct gooseData
        {
            /// <summary>
            /// 目标MAC
            /// </summary>
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
            public byte[] DMAC;
            /// <summary>
            /// 源MAC
            /// </summary>
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
            public byte[] SMAC;
            /// <summary>
            /// TPID=0x8100
            /// </summary>
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
            public byte[] TPID;
            /// <summary>
            /// TCI=0x8000
            /// </summary>
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
            public byte[] TCI;
            /// <summary>
            /// APPID=0x88b8
            /// </summary>
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
            public byte[] APPID;
            /// <summary>
            /// data=110(bytes)
            /// </summary>
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 110)]
            public byte[] Data;

        }
我以太网收到一帧数组(128个字节)数据,然后想把数据放入以上结构体中,然后从结构体内取值、显示。请各位帮帮忙!!
搜索更多相关主题的帖子: 结构体 
2010-11-29 10:50
makebest
Rank: 8Rank: 8
等 级:蝙蝠侠
威 望:3
帖 子:658
专家分:962
注 册:2005-3-17
得分:20 
花了点时间搞出来了
程序代码:
gooseData ConvertFromArray(byte[] txt)
{
    IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(gooseData)));
    if (p != IntPtr.Zero)
    {
        try
        {
            int size = Marshal.SizeOf(typeof(gooseData));
            Marshal.Copy(txt, 0, p, Math.Min(size, txt.Length));
            gooseData s = (gooseData)Marshal.PtrToStructure(p, typeof(gooseData));
            return s;
        }
        finally
        {
            Marshal.FreeHGlobal(p);
        }
    }
    throw new Exception("Out of memory");
}

2010-12-01 10:15
linlvbin
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2010-11-29
得分:0 
谢谢黑侠的指导!
问下,你这里的txt是从文本中读吗?我是直接从以太网收的数据。我先试试你的。
2010-12-01 15:04



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-327220-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.073017 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved