简体   繁体   English

C ++ / CLI结构/类对齐

[英]C++/CLI struct / class alignment

It seems I cannot make C++/CLI structures be aligned with less than 8 bytes. 看来我无法使C ++ / CLI结构的对齐方式少于8个字节。 I have a struct of two Int32, allocate a million of them, and voilà: 16 MB memory according to ".NET Memory Profiler" (plus the list data). 我有一个两个Int32的结构,分配一百万个,然后贴上:根据“ .NET Memory Profiler”的16 MB内存(加上列表数据)。 I set the compiler option to /Zp4 (also tried /Zp1), to Minimize Size (/O1) and Small Code (/Os), just to make sure, I additionally put a "#pragma pack(1)" into my code, to no avail. 我将编译器选项设置为/ Zp4(也尝试过/ Zp1),以最小化大小(/ O1)和小代码(/ Os),只是为了确保,我还在代码中添加了“ #pragma pack(1)” ,无济于事。 My struct is still taking up 16 Bytes. 我的结构仍然占用16个字节。 I changed it to class, still the same. 我将其更改为类,仍然相同。

Why that? 为什么? How to change? 如何改变?

Ciao, Eike 乔爱克

using namespace System;
#pragma pack(1)

ref struct myStruct
{
    Int32 a;
    Int32 b;
};

int main(array<System::String ^> ^args)
{
    System::Collections::Generic::List<myStruct^> list;
    for (int i = 0; i < 1000000; i++)
    {
        list.Add(gcnew myStruct());
    }
    // avoid optimization
    Console::WriteLine(list[333333]->a);
    return 0;
}

You need to use value types to be able to specify alignment. 您需要使用值类型才能指定对齐方式。 Beyond that I'm not sure this is the best way to measure this. 除此之外,我不确定这是否是衡量这一点的最佳方法。 Reference types also have some small built in overhead. 引用类型也有一些小的内置开销。 Try value struct/value class instead. 请尝试使用值struct / value类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM