#pragma 包效果 [英] #pragma pack effect

查看:25
本文介绍了#pragma 包效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以向我解释 #pragma pack 预处理器语句的作用,更重要的是,为什么要使用它.

I was wondering if someone could explain to me what the #pragma pack preprocessor statement does, and more importantly, why one would want to use it.

我查看了 MSDN 页面,其中提供了一些见解,但我希望从有经验的人那里听到更多.我以前在代码中看到过,但我似乎再也找不到在哪里了.

I checked out the MSDN page, which offered some insight, but I was hoping to hear more from people with experience. I've seen it in code before, though I can't seem to find where anymore.

推荐答案

#pragma pack 指示编译器以特定对齐方式打包结构成员.大多数编译器,当你声明一个结构体时,会在成员之间插入填充以确保它们与内存中的适当地址对齐(通常是类型大小的倍数).这避免了与访问未正确对齐的变量相关的某些体系结构上的性能损失(或彻底错误).例如,给定 4 字节整数和以下结构:

#pragma pack instructs the compiler to pack structure members with particular alignment. Most compilers, when you declare a struct, will insert padding between members to ensure that they are aligned to appropriate addresses in memory (usually a multiple of the type's size). This avoids the performance penalty (or outright error) on some architectures associated with accessing variables that are not aligned properly. For example, given 4-byte integers and the following struct:

struct Test
{
   char AA;
   int BB;
   char CC;
};

编译器可以选择像这样在内存中布置结构:

The compiler could choose to lay the struct out in memory like this:

|   1   |   2   |   3   |   4   |  

| AA(1) | pad.................. |
| BB(1) | BB(2) | BB(3) | BB(4) | 
| CC(1) | pad.................. |

sizeof(Test) 将是 4 ×3 = 12,即使它只包含 6 个字节的数据.#pragma(据我所知)最常见的用例是在使用硬件设备时,您需要确保编译器不会将填充插入数据并且每个成员都遵循前一个.使用 #pragma pack(1),上面的结构体的布局如下:

and sizeof(Test) would be 4 × 3 = 12, even though it only contains 6 bytes of data. The most common use case for the #pragma (to my knowledge) is when working with hardware devices where you need to ensure that the compiler does not insert padding into the data and each member follows the previous one. With #pragma pack(1), the struct above would be laid out like this:

|   1   |

| AA(1) |
| BB(1) |
| BB(2) |
| BB(3) |
| BB(4) |
| CC(1) |

sizeof(Test) 将是 1 ×6 = 6.

And sizeof(Test) would be 1 × 6 = 6.

如果使用 #pragma pack(2),上面的结构体将如下所示:

With #pragma pack(2), the struct above would be laid out like this:

|   1   |   2   | 

| AA(1) | pad.. |
| BB(1) | BB(2) |
| BB(3) | BB(4) |
| CC(1) | pad.. |

sizeof(Test) 将是 2 ×4 = 8.

And sizeof(Test) would be 2 × 4 = 8.

struct 中变量的顺序也很重要.变量排序如下:

Order of variables in struct is also important. With variables ordered like following:

struct Test
{
   char AA;
   char CC;
   int BB;
};

并且使用 #pragma pack(2),结构体的布局如下:

and with #pragma pack(2), the struct would be laid out like this:

|   1   |   2   | 

| AA(1) | CC(1) |
| BB(1) | BB(2) |
| BB(3) | BB(4) |

sizeOf(Test) 将是 3 × 2 = 6.

and sizeOf(Test) would be 3 × 2 = 6.

这篇关于#pragma 包效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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