Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to send structs as neatly sorted packets using iPhone Game Kit..

I have a struct which looks like:

typedef struct {
   int coolStuff;
   char playerID[100];
} MyStruct;

Then I'm using strncpy() to copy the NSString I want into MyStruct.playerID. However, I would like to be able to send a playerID (string) of any size and possibly multiple strings per struct. Any suggestions?

There is a chance I'm making this more difficult than it actually is..

share|improve this question

Google's Protocol Buffers is a project designed to help with this kind of thing. Makes it somewhat easy to move structs around between memory, network, disk, et al.

share|improve this answer
Maybe I'm a little out of my element here.. but does this work with IPhone GameKit?.. I mistakenly left that out. Sorry! – pleasedontlaugh Jul 28 '10 at 1:11 looks like it will do exactly that, but I can't say I've used it or had heard of it 5 minutes ago. – coderanger Jul 28 '10 at 1:17
cool.. ill check this out. thanks! – pleasedontlaugh Jul 28 '10 at 2:53

The fundamental thing you need to do is just have code on one side that knows how to serialize data, and code on the other that knows how to deserialize.

So, for variable length strings, just send the length first:

   n = strlen(playerid) + 1; // for NULL terminator

and then on the receiving side get the length, and read that many bytes.:

   int n;
   char *s;
   s = malloc(n)

Of course, what you should really do is gather up your communication into packets, and then send blocks of data at once with headers, have type info in a debug mode for safety, etc. but that's the gist of it.

Google protocol buffers look like they are a way of turning data into something serializable, so in that version of this example send and recv would be an XML string, which is great for general servers, but you may want more explicit control.

share|improve this answer
Protobufs are significantly more compact than XML, and have both a text (JSON-esque) and binary form. Otherwise, I agree, it's good to know how this stuff works under the hood. – user744 Aug 31 '10 at 19:22

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.