结构.NET尺寸 [英] Size of structures in .NET

查看:144
本文介绍了结构.NET尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是在C程序之间发送的结构,以C#程序。

My problem is to send a structure between a program in C to a C# program.

我在C#中做了一个结构:

I made a structure in C#:

public struct NetPoint {
    public float lat; // 4 bytes
    public float lon; // 4 bytes
    public int alt; // 4 bytes
    public long time; // 8 bytes
}

的结构的总的大小必须是20字节。

The total size of the structure must be 20 bytes.

当我做了的sizeof() C语言这种结构++

When I do a sizeof() in C++ of this structure,

System.Diagnostics.Debug.WriteLine(
    "SizeOf(NetPoint) = " +
    System.Runtime.InteropServices.Marshal.SizeOf(new NetPoint()));

调试控制台显示:

the debug console shows:

一下SizeOf(NetPoint)= 24

SizeOf(NetPoint) = 24

不过,我预计将有20个字节。为什么我看到一个区别?

But I expected to have 20 bytes. Why do I see a difference?

推荐答案

其实,在技术上的结构必须是一个 最小 20个字节。如果您在发送时分配更多的,接收器就不会使用/复制它们。问题是始终分配不足

Actually, technically the structure must be a minimum of 20 bytes. If you allocate more when sending, the receiver just won't use / copy them. The problem is always underallocation.

不过,我看这个问题。嗯。我认为这个问题是在过去很长....这恕我直言,被对准八个字节,注射前4个空字节。我认为这是对具有不对齐​​到8字节边界八字节元件的性能损失。

That said, I see the problem. Hmm. I think the problem is the last long.... which IMHO gets aligned to eight bytes, injecting four empty bytes before. I think there is a performance penalty for having an eight-byte element not aligned to an eight-byte boundary.

连接<一href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx"相对=nofollow> StructLayout 属性,以确定每个元素的手动偏移。然后,你应该能够得到的东西的行。

Attach StructLayout attributes to determine the offset of every element manually. Then you should be able to get things in line.

参考: 如何控制在.NET Framework 2.0 <数据字段的物理布局/ A>

[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct NetPoint {  
    public float lat; // 4 bytes 
    public float lon; // 4 bytes 
    public int alt; // 4 bytes 
    public long time; // 8 bytes 
} 

这至少应对准元件以一个字节边界。您可以通过定义每个元素的确切的开始,也是如此,如果需要进一步的去了。

That at least should align elements to a one-byte boundary. You can go further by defining the exact start of every element, too, if needed.

这篇关于结构.NET尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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