I have the following code:
eachShape(void *ptr, void* unused) {
cpShape *shape = (cpShape *) ptr;
id obj = shape->data;
NSLog(@"shape->data: %@", obj); // this is where EXC_BAD_ACCESS can occur
...
Some of you may recognize it from the Chipmunk physics framework used in iPhone development. Basically I crash here because of something I am doing in other code regarding the cpSpace, but I want to figure out what object type is getting sent here and crashing my NSLog sta开发者_如何学Gotement (and causing other havoc).
What is the best way to dump the type and/or contents from a void pointer to an NSLog call?
I think your problem is that %@
is only meaningful if shape->data
really points to an Objective-C object, since using it triggers the sending of -description
to obj
.
But if for example shape->data
points to an int
, the message will be send to an object that does not really exists. Instead, some memory location may be interpreted as the raw bytes of an object, causing the runtime to crash.
To answer your question: The type of an void pointer is void *
, and the type of the pointer's target is void
. You can print the pointer's value with %p
, but I doubt that this is what you want.
So if you are sure that the memory location where shape->data
points to represents an Objective-C object, and you have access to the class code, you can override -description
to print whatever information you like.
The %@
format specifier is interpreted as
Objective-C object, printed as the string returned by
descriptionWithLocale:
if available, ordescription
otherwise. Also works withCFTypeRef
objects, returning the result of theCFCopyDescription
function.
Basically, if ptr
doesn't point to an Objective-C object, you're out of luck!
Either way, you should cast the void *
pointer to something meaningful..
精彩评论