I’m (trying) to write some (working) C++ in an ObjC project 🙂 The C++ library (Box2D) provides me with a b2Fixture class which has a “user data” property for coders to store whathever is relevant to them.
In my case, it simply has to store an integer. From my main program in ObjC, one is to cast the integer to void*:
headFixture->SetUserData( (void*) 10 );
In a utility method on the C++ side of the program, I would like to compare the user data to a given integer (i.e. they’re constants, 10 = solid ground, 11 = platform, etc.).
First comparison uses (void*) which refuses to compile. Found on SO a different approach, like illustrated by the second comparison which uses *( (intptr_t *) … ). That one compiles, but it sends EXC_BAD_ACCESS:
bool AbstractContactListener::contactContainsType(JRContact contact, int type){
if (( type == ( (void *) contact.fixtureA->GetUserData() )) ||
( type == *( (intptr_t *) contact.fixtureB->GetUserData() ))
) {
return true;
}
return false;
}
I’m running out of ideas to approach this issue.
Please help 🙂
Thanks!
J.
EDIT/SOLUTION:
bool AbstractContactListener::contactContainsType(JRContact contact, int type){
if (( type == (intptr_t) contact.fixtureA->GetUserData() ) ||
( type == (intptr_t) contact.fixtureB->GetUserData() )
) {
return true;
};
return false;
}
This one worked for me!
As far as I can see, you just need to cast it back; you need to use an integer type that’s guaranteed to be the same size as a pointer to cast via or the compiler may error out;
There is one caveat though, as far as I know, the cast int to void* and back is not guaranteed by the C standard to give back the same value. A safer option may be to just use pointers as they are ment to be used;
and
which shouldn’t tempt any compiler to break your code.