Marshal.Sizeof()返回意外值 [英] Marshal.Sizeof() returning unexpected value

查看:67
本文介绍了Marshal.Sizeof()返回意外值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调试由第三方编写的C#代码.该项目是一个老的C ++项目,由承包商用C#重写,我无法访问该承包商.我编写了原始的C ++版本.

I'm debugging code in C# written by a 3rd party. The project is an old C++ project that was rewritten in C# by a contractor, and I have no access to the contractor. I authored the original C++ version.

问题是C#代码获得表示通过UDP连接接收的数据的结构的大小时.

The issue is when the C# code gets the size of a structure that represents data received over a UDP connection.

该结构定义为:

[StructLayout(LayoutKind.Sequential,Pack=1)]
internal class PROXY_HDR {
    public ushort pad;
    public ushort label;
    public char flags;
    public ushort length;
    public char[] ip = new char[4];
    public ushort port;
}

此结构的大小检索为:

int size = Marshal.Sizeof(typeof(PROXY_HDR));

并且返回的值是 17 而不是预期的 13.有 4 个字节的差异,我怀疑 ip 成员,但这仅仅是因为它的表达方式与其他成员不同(带有新"),但我没有其他决定依据.

and the value returned is 17 instead of the expected 13. With a 4-byte difference, I suspect the ip member, but only because it's expressed differently than the other members (with 'new'), but I have no other basis to decide.

我通常不会在解析接收到的数据包的问题的C#代码中使用这种封送处理,因此我不知道如何修改此结构定义以使其与原始版本大小对齐",明智的.

I don't typically use this type of marshaling in my C# code that parses received packets without a problem, so I don't know how to modify this struct definition to make it 'line up' with the original version size-wise.

我可以将元帅行替换为

int size = 13;

但这是作弊吧?

我可以以某种方式修改此布局以使尺寸正确显示吗?

Can I modify this layout somehow to get the size to come out right?

推荐答案

将其添加到结构中:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal class PROXY_HDR
{
    public ushort pad;
    public ushort label;
    public byte flags;
    public ushort length;
    [MarshalAs(UnmanagedType.ByValArray,
        SizeConst = 4, ArraySubType = UnmanagedType.U1)]
    public byte[] ip;
    public ushort port;
}

这将告诉编译器将其视为典型的C样式数组,而不是指针.该应该为字节,因为IP地址是一个无符号的char数组.char 通常不用于这些类型的标头,它通常是 byte(即:unsigned char)

This will tell the compiler to treat it as a typical C-style array, not a pointer. This should be byte, as an IP address is an unsigned char array. char typically isn't used in these types of headers, it's usually byte (i.e: unsigned char)

这篇关于Marshal.Sizeof()返回意外值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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