在c中通过消息队列进行类型转换

时间:2015-05-31 11:51:01

标签: c linux casting ipc

我目前正在尝试通过消息队列发送整数。我将此整数的地址类型转换为(char *),因为将来我希望接受其他数据类型,并且此数据在设计用于消息队列的结构中发送。

通过消息队列(我已经验证其工作正常),我发送了一个结构类型:

struct Type{

    long mtype;
    char *data;
};

要发送消息,将从发送过程执行以下代码:

struct Type* ack = malloc(sizeof(struct Type));
int temp = 999;

ack->mtype = 1;
ack->data = (char *)&temp;


if(msgsnd(msqid, ack, sizeof(struct Type) - sizeof(long), 0) == -1){

          perror("Sending acknowledgement to producer\n");

}

在接收端,然后执行以下操作:

struct Type *rack = malloc(sizeof(struct Type));

rack->mtype = 1;

//Wait for acknowledgement from server
if(msgrcv(prodmsqid, rack, sizeof(struct Type) - sizeof(long), 0, 0) == -1){ 

       perror("msgrcv for acknowledgement from server");

            exit(1);


 }
 printf("Acknowledgement has arrived: %d\n",(int)rack->data);

此printf的输出从非常大的数字(8171536)变为4。

2 个答案:

答案 0 :(得分:0)

struct Type{

    char *data;
    long mtype;
};

那会给你你想要的东西。

答案 1 :(得分:0)

我认为问题在于你传递的是堆栈中的地址,int地址被转换为char地址。但是这个int位置在发送之后就超出了范围。如果我正确的话,一个解决办法是将int位置设为全局。