0

我为移动定义了一个结构

typedef struct {
    MsgType msgType;
    int newFallenStonesSize;
    char *newFallenStones;
} MsgMove;

并像这样发送数据:

MsgMove message;
message.msgType = MsgTypeMove;     
message.newFallenStones = (char *)malloc(nrNewFallenStones*sizeof(char));
for (int i=0; i<nrNewFallenStones; i++) {
    message.newFallenStones[i]=newFallenStones[i];
}
message.newFallenStonesSize = nrNewFallenStones;

NSData *data = [NSData dataWithBytes:&message length:(2*sizeof(int)+message.newFallenStonesSize*sizeof(char))];          

[[KKGameKitHelper sharedGameKitHelper] sendDataToAllPlayers:data reliable:YES]; 

发送时数据是正确的,但是当我像这样收到它时:

else if (msg->msgType == MsgTypeMove)
{
    MsgMove *msgMove = (MsgMove *) [data bytes]; 
    for (int i=0; i<msgMove->newFallenStonesSize; i++) {
        NSLog(@"New Stone received:%i",msgMove->newFallenStones[i]);
    }
}

价值观发生了变化。例如 1、6、3,我收到 76、105 98。

任何人都知道为什么会这样?

4

1 回答 1

2

主要问题是您通过网络发送指向数据的指针,而不是实际数据。当您对其进行 malloc 空间时,message.newFallenStones它将被设置为内存中与您的MsgMove结构不相邻的某个明显随机的位置。然后,您将数据写入此其他内存位置。您打包传输的是 MsgMove 结构(带有指向内存中其他位置的指针)加上内存中紧随其后的任何随机字节。

处理这种情况的典型方法是让您的整个消息被 malloc'ed 在一起并将数据写入它的末尾。更像:

typedef struct {
    MsgType msgType;
    int newFallenStonesSize;
    char newFallenStones;        // The first newFallenStones value
} MsgMove;

然后发送

MsgMove *message;
message = (MsgMove *)malloc(sizeof(MsgMove)+nrNewFallenStones-1);
message->msgType = MsgTypeMove;     
message->newFallenStonesSize = nrNewFallenStones;
char *newStones = &MsgMove->newFallenStones;
for (int i=0; i<nrNewFallenStones; i++) {
    newStones[i]=newFallenStones[i];
}

NSData *data = [NSData dataWithBytes:message length:(sizeof(MsgMove)+nrNewFallenStones-1)];          

[[KKGameKitHelper sharedGameKitHelper] sendDataToAllPlayers:data reliable:YES]; 
于 2012-07-09T15:30:08.323 回答