Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a C array of C structs in NSData

I've got a really simple C struct like so:

typedef struct {
    int tag;
    CGPoint position;
} Place;

That is, all scalar types and no pointers in the struct.

Then I've got an array of those points like so:

 Place *dynamicPlaces = calloc(numberOfPlaces, sizeof(Place));

So each element of dynamicPlaces ought to be (unless I've mixed something up… it's certainly possible with me and pointers…) a struct of type Place, initialized with all its members to 0, yeah? So far so good.

Then I'm trying to put that array in an NSData object to be sent over the network (along with the count of elements, not shown):

NSData *placesData = [NSData dataWithBytes:dynamicPlaces length:(sizeof(Place) * numberOfPlaces)];

I'm passing it the array directly, because if memory serves, the pointer dynamicPlaces is really pointing to the first struct element of the array, and then I tell it how many elements there are via length. I think this is good.

Finally, on the other side I do this when decoding my object.

[receivedData getBytes:receivedDynamicPlacesArrayPointer length:[receivedData length]];

But I get an EXC_BAD_ACCESS on that line and I can't quite figure out why. As far as I can tell by the documentation, this ought to be storing the bytes from the NSData into a copied location in memory, and point to that blob with receivedDynamicPlacesArrayPointer.

It's entirely possible I've made a mistake doing this, pointers trip me up, even though I think I understand them. Any help would be greatly appreciated.

like image 682
jbrennan Avatar asked Dec 09 '25 03:12

jbrennan


1 Answers

getBytes:length: docs say: "Copies a number of bytes from the start of the receiver's data into a given buffer."

So you will need to first allocate memory for receivedDynamicPlacesArrayPointer yourself. Did you do that?

In other words, you'd do like:

 Place* receivedDynamicPlacesArrayPointer = (Place*)malloc([receivedData length]);
like image 198
Ken Aspeslagh Avatar answered Dec 10 '25 18:12

Ken Aspeslagh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!