Thursday, October 29, 2009

Note to Self on Void Pointers and CallFuncND

This is no news to anyone except for people who have never been exposed to void pointers (void*) before. Coming from a Java-background, I never had the opportunity (or dare I say hassle) to deal with pointers, obtaining memory addresses and de-referencing those. Whenever I was confronted with C / C++, I tried my best not to dive too deep into that matter.

Now in Objective C, I finally wanted to get rid of a compiler warning I was getting because I was dealing with void* as a data type. Basically, void* is a pointer to some data in memory of which the type is unknown to the compiler. Therefore, any address to some data in memory can be stuffed into a variable of type void*. Both of the following is valid:

void* data;
int i = 5;
float f = 6.5;

data = &i; // first assignment: works
data = &f; // second assignment: works, too

Now to get back to the data you stuffed inside, you cannot just de-reference it just like that. You need to cast it to the proper pointer type of the data that is stored at the particular address you're pointing to. In other words, you'd have to do the following (continuing the code above):

int* iPtr = (int*) data; // if data contains &i
float* fPtr = (float*) data; // if data contains &f

Since cocos2d uses void* as the data type to piggy-back any kind of user data within a CallFuncND action, I at least had to get that straight!

No comments:

Post a Comment