C 具有结构和int的共享内存

C 具有结构和int的共享内存,c,pointers,shared-memory,C,Pointers,Shared Memory,因此,我有一个问题,我想添加“一”结构和一个int到我的共享内存 我想把我的“int”放在共享内存的第一个位置(因为我在其他程序中需要这个int),然后得到结构 这是我的密码 int id = shmget( 0x82488, (sizeof(student)) + sizeof(int) ,IPC_CREAT | 0666 ); exit_on_error (id, "Error"); int *p = shmat(id,0,0); exit_on_null(p,"Erro no attac

因此,我有一个问题,我想添加“一”结构和一个int到我的共享内存 我想把我的“int”放在共享内存的第一个位置(因为我在其他程序中需要这个int),然后得到结构 这是我的密码

int id = shmget( 0x82488, (sizeof(student)) + sizeof(int) ,IPC_CREAT | 0666 );
exit_on_error (id, "Error");

int *p = shmat(id,0,0);
exit_on_null(p,"Erro no attach");

Student *s = shmat(id,0,0);
exit_on_null (s,"Error");
现在我的问题来了,因为我有两个指针,我怎样才能使int成为第一个,然后是结构,我应该这样做吗

p[0]=100 s[1] = (new Student)
我会的

int *p = shmat(id,0,0);
exit_on_null(p,"Erro no attach");

Student *s = (Student*)(void*)(p + 1);
因此,
s
指向下一个int的位置,如果它是int

这有点棘手,但可以通过在结构中填充字节来清除所有可能的互操作问题

例如:

+---+---+---+---+---+---+---+---+---+---+
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
+---+---+---+---+---+---+---+---+---+---+
在这种情况下,
p
指向位置0(相对于缓冲区的开始),因此
p+1
指向位置4(如果
int
有32位)。用我的方式铸造
p+1
使得pont
s
来到了这个地方,但类型是
Student*

如果要添加结构
struct extension
,请执行相同的操作:

struct extension *x = (struct extension*)(void*)(s + 1);

它紧跟在
Struct
的后面,并且同样具有正确的指针类型。

为什么不编写
Struct shared\u mem{int count;Student s;}
?然后,您只需要一个指向此结构的指针,就可以访问所有共享内存。您从
shmat
获得的内存针对所有可能的数据类型对齐。前面的内存
4
字节可能与您的结构不正确对齐。@WernerHenze我不使用该解决方案,因为我只需要该数字once@Ventura但是你认为这种结构的缺点是什么?拥有该号码但不使用它的成本是多少?如何做两个
shmat
来减少负载?我不太明白,但我不想s指向int,我想能够访问内存,能够先得到int,然后得到structure@Ventura但是你想让它紧跟在你的第一个int后面,是吗?假设我们有一个多对象数组数组*
array[0]=int数组[1]=structure数组[2]=structure
类似这样的问题是如何实现
Student*s=(Student*)(void*)(p+1)错误地假设
p+1
对于
Student
对象正确对齐。