数组的内存对齐 [英] Memory alignment of arrays
问题描述
我无法在Cell处理器上对齐内存以进行DMA传输.我需要地址的后4位为0.
I am having trouble aligning memory for DMA transfer on the Cell processor. I need the last 4 bits of an address to be 0.
我有4个unsigned int
数组,其中每个元素必须在内存中对齐,以便其(十六进制)地址以零结尾.
I have 4 arrays of unsigned int
where each element must be aligned in memory so that its (hex) adress ends with a zero.
例如
int main()
{
size_t i;
static unsigned int a[2] __attribute__ ((aligned (16)));
static unsigned int b[2] __attribute__ ((aligned (16)));
static unsigned int c[2] __attribute__ ((aligned (16)));
static unsigned int d[2] __attribute__ ((aligned (16)));
for (i = 0; i < 2; ++i) {
printf("a[%u] = %p\n", &a[i]);
printf("b[%u] = %p\n", &b[i]);
printf("c[%u] = %p\n", &c[i]);
printf("d[%u] = %p\n", &d[i]);
}
return 0;
}
输出:
a[0] = 0x10010b60
b[0] = 0x10010b50
c[0] = 0x10010b40
d[0] = 0x10010b30
a[1] = 0x10010b64
b[1] = 0x10010b54
c[1] = 0x10010b44
d[1] = 0x10010b34
这里的问题是每个数组的第二个元素似乎没有对齐16位(它们的地址以4结尾).
The problem here is that the 2nd element of each array doesn't seem to be 16-bit aligned (their address' end with a 4).
我需要的地址看起来像这样:
I need the addresses to look like this:
a[0] = 0xXXXXXXX0
b[0] = 0xXXXXXXX0
c[0] = 0xXXXXXXX0
d[0] = 0xXXXXXXX0
a[1] = 0xXXXXXXX0
b[1] = 0xXXXXXXX0
c[1] = 0xXXXXXXX0
d[1] = 0xXXXXXXX0
推荐答案
alignment属性指定变量或结构字段的对齐方式,而不是单个数组元素.有关详细信息,请参见指定变量属性.
The alignment attribute specifies the alignment of variables or structure fields, not single array elements. See Specifying Attributes of Variables for details.
如果始终要将两个整数对齐,则可以定义结构
If you always want to align two integers together, you can define a structure
struct dma_transfer {
unsigned int e0 __attribute__ ((aligned (16)));
unsigned int e1 __attribute__ ((aligned (16)));
};
这会将元素对齐在16个字节的边界上.
This aligns the elements on 16 byte boundaries.
int main(int argc, char **argv)
{
static struct dma_transfer a;
static unsigned int b[2];
printf("a.e0 = %p\n", &a.e0);
printf("a.e1 = %p\n", &a.e1);
printf("b[0] = %p\n", &b[0]);
printf("b[1] = %p\n", &b[1]);
return 0;
}
给予,例如
a.e0 = 0x601060
a.e1 = 0x601070
b[0] = 0x601080
b[1] = 0x601084
但这也意味着您在两个整数值之间有孔.在32位系统上,您将拥有
But this means also, that you have holes between the two integer values. On a 32 bit system, you will have
| int 4个字节|洞12个字节|
| int 4个字节|洞12字节|
| int 4 bytes | hole 12 bytes |
| int 4 bytes | hole 12 bytes |
这篇关于数组的内存对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!