Return Obj-C blocks in C++ code
I'm currently porting some classes from the Apple iOS Foundation Framework to C++ and i'm expecting some issues. I'm trying to port this Obj-C method from the NSExpression @class :
- (id, NSArray *, NSMutableDictionary *)expressionBlock
So in my sfExpression class, I have the following code (when deleting others methods ^^)
class sfExpression : public sfObject {
public:
id (^Expr开发者_运维知识库essionBlock())(id, NSArray*, NSMutableDictionary*);
private:
NSExpression* _Expression;
};
And when I'm trying to implement this function like this :
id (^sfExpression::ExpressionBlock())(id, NSArray*, NSMutableDictionary*) {
return [_Expression expressionBlock];
}
It doesn't work... Any ideas ?
I've tried many things but... without success :'(
EDIT : The code is right. Just switch to LLVM Compiler instead of GCC
Edit: Moral of the story, don't use GCC when dealing with blocks.
Here is a full example as far as I can see, this works in my tests.
class Foo
{
public:
Foo(NSExpression *_exp) : expression([_exp retain])
{
}
~Foo()
{
[expression release];
}
id (^ExpressionBlock())(id, NSArray*, NSMutableDictionary*);
private:
NSExpression *expression;
};
id (^Foo::ExpressionBlock())(id, NSArray*, NSMutableDictionary*)
{
return [expression expressionBlock];
}
int main()
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
Foo a([NSExpression expressionForBlock:^id(id evaluatedObject, NSArray *expressions, NSMutableDictionary *context) {
return evaluatedObject;
} arguments:[NSArray arrayWithObject:@"Test"]]);
NSLog(@"%@", a.ExpressionBlock()(@"Hello", nil, nil));
[pool drain];
}
/usr/include/Block.h
manipulates ObjC blocks using opaque void pointers, so that's probably what you should use to pass them around to C++ code if you can't compile it with a compiler supporting blocks. Also take note of the Block_copy and Block_release functions in that header. There's also an article on memory management of ObjC blocks.
精彩评论