tags:

views:

29

answers:

2

Hi,

I will like to do some kind of forwarding in my mixed C++/ObjC project.

My logic is in C++, and I want to provide a method that belongs to a C++ object instance as a selector to objC. Is there anyway to do this?

Mainly the question is, Is there anyway to fake a C++ method into a selector :), to give it to ObjC and let it be called back?.

Thanks in advance, Anoide.

+1  A: 

It is impossible to get a selector for a C++ method as these are not managed by the Objective-C runtime. You can, however:

  • Use a normal C++ function pointer to implement a callback
  • Or: Create an Objective-C method (best would be a class method) to wrap the call to your C++ method. You can use the selector for this function then.
Johannes Rudolph
A: 

You could wrap the C++ object in an Objective-C proxy object:

@interface MyObjCClass: NSObject {
  MyCPPClass *thing;
}
-(int)foo;
@end

@implementation MyObjCClass {

  -(id)init {
    if (self = [super init]) {
      thing = new MyCPPClass();
    }
    return self;
  }

  -(void)dealloc {
    delete thing; // It's been a long time since I last did C++; I may have the incorrect syntax here
    [super init];
  }

  -(int)foo {
    return thing->foo();
  }
}
@end
Frank Shearar