2012-09-06 72 views
1

我正在实现Box2d(用C++编写)的目标C封装器。 b2Body在其userData字段中保留对其包装器的引用。 GetUserData返回一个void *。我现在正在实施快速迭代,以便将B2B实体从B2World中提取出来。'从不兼容类型'分配'id'

我在下面指示的行中得到'来自不兼容类型'B2Body *'错误的'分配给'id'。为什么?

#import "B2Body.h" 
#import "B2World.h" 
#import "Box2d.h" 

@implementation B2World 

-(id) initWithGravity:(struct B2Vec2) g 
{ 
    if (self = [super init]) 
    { 
    b2Vec2 *gPrim = (b2Vec2*)&g; 
    _world = new b2World(*gPrim); 
    } 

    return self; 
} 

- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained [])buffer count:(NSUInteger)len; 

{ 
    if(state->state == 0) 
    { 
    state->mutationsPtr = (unsigned long *)self; 
    state->extra[0] = (long) ((b2World*)_world)->GetBodyList(); 
    state->state = 1; 
    } 

    // pull the box2d body out of extra[0] 
    b2Body *b = (b2Body*)state->extra[0]; 

    // if it's nil then we're done enumerating, return 0 to end 
    if(b == nil) 
    { 
    return nil; 
    } 

    // otherwise, point itemsPtr at the node's value 
    state->itemsPtr = ((B2Body*)b->GetUserData()); // ERROR 
    state->extra[0] = (long)b->GetNext(); 

    // we're returning exactly one item 
    return 1; 
} 

`

B2Body.h看起来像这样: #进口

@interface B2Body : NSObject 
{ 
    int f; 
} 

-(id) init; 
@end 
+0

下面哪条线表示? – deanWombourne

+0

标有// ERROR –

+0

的那个啊,对不起。我是盲人:) – deanWombourne

回答

2

NSFastEnumerationState是C结构,itemsPtr字段是:

id __unsafe_unretained *itemsPtr; 

在较早版本,__unsafe_unretained说明符是明显缺失。

请注意,字段itemsPtr是一个指针ID。由于id本质上是一个指针,因此itemsPtr是一个指向对象指针的指针。实际上,这个字段是持有允许快速枚举的对象数组的对象。基本上,它通过这个对象指针数组。

由于我对Box2d一无所知,这就是我所能说的。假定B-> GetUserData()返回一个指向对象的数组,你应该能够做到这一点:

state->itemsPtr = (__unsafe_unretained id *)b->GetUserData(); 

虽然有点过时,Mike Ash's article仍然实现快速列举的重要来源。

编辑

只注意到你是返回一个对象。所以,我假设GetUserData只返回一个对象指针。既然你需要返回一个指向对象的指针,你需要做这样的事情:

id object = (__bridge id)b->GetUserData(); 
state->itemsPtr = &object; 

然而,栈对象将会消失,一旦你从这个方法,这就是为什么你传递一个堆栈返回你可以使用缓冲区。因此,您应该将该单指针填充到提供的堆栈缓冲区中:

*buffer = (__bridge id)b->GetUserData() 
state->itemsPtr = buffer; 
相关问题