6

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.

2 Answers 2

3

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.
Sign up to request clarification or add additional context in comments.

1 Comment

nb: use a normal C++ function pointer to implement a callback is complicated
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.