开发者

How to add tag (identifier) to box2D object (objective - c)

i'm developing an app that uses Box2d. When I try to do something like this :

开发者_如何学Python
NSString *s = @"wood";

bodyDef.userData.name = s; 

I get error

request for member 'name' in 'bodyDef.b2BodyDef::userData', which is of non-class type 'void*'

Thanks!


You cannot dereference a void* pointer in C, C++, or Objective-C. A void* pointer is a pointer to an unknown data type -- when you use one, you're telling the compiler that "it points to something, but I have no idea what exactly that something is".

When you assign your user data to a Box2D object, it treats it as an opaque pointer: it copies it around as needed, but it never looks at what data the pointer points to. That's your job.

In order to get a usable pointer back out, you just need to cast it (implicitly or explicitly) to the correct type. Assuming you're using a common data structure, you can do something like this:

struct MyUserData
{
    NSString *name;
    // other data
};
...
// Allocate and initialize the user data
MyUserData *userData = malloc(sizeof(MyUserData);
userData->name = @"wood";
// etc.
bodyDef.userData = userData;

...

// To access the data, use an explicit cast or an implicit cast:
NSString *name = ((MyUserData *)bodyDef.userData)->name;  // explicit

MyUserData *userData = bodyDef.userData;  // implicit
NSString *name = userData->name;

Note that you can only make an implicit cast from void* to other pointer types in C and Objective-C -- doing so is illegal in C++ and Objective-C++ and requires an explicit cast.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜