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..


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.

  • \$\begingroup\$ Maybe I'm a little out of my element here.. but does this work with IPhone GameKit?.. I mistakenly left that out. Sorry! \$\endgroup\$ – pleasedontlaugh Jul 28 '10 at 1:11
  • \$\begingroup\$ code.google.com/p/metasyntactic/wiki/ProtocolBuffers looks like it will do exactly that, but I can't say I've used it or had heard of it 5 minutes ago. \$\endgroup\$ – coderanger Jul 28 '10 at 1:17

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.

  • \$\begingroup\$ 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. \$\endgroup\$ – user744 Aug 31 '10 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy