从 C++ 对象调用 Objective-C 父级

Calling Objective-C parent from C++ object

在 iOS 上创建音频单元扩展需要混合使用 C++ 和 Objective-C 类。结果,我现在有一个 Objective-C 对象,其中一个 C++ 对象作为其变量之一。

我希望 C++ 子对象能够将某些状态更改通知其 Objective-C parent/owner。

在伪代码中:

void cppChildObject::callMom() {
   objectiveCParent::notificationMethod();
}

这有可能以优雅的方式实现吗?

这取决于您如何定义优雅...如果 C++ class 位于 Objective-C++ 文件(扩展名为 .mm 的文件)中,这可能以一种相当优雅的方式实现并且不被不在 Objective-C++ 源文件中的 C++ 代码直接使用。问题是 C++ 代码只能在 Objective-C++ 源文件中使用 Objective-C 类型。这是一个简单的示例,希望对您有所帮助。

Objective-C++ 文件,mylib.mm(注意.mm 扩展名):

#import "objcpp.h"
#import <stdio.h>
#import "cpp.h"

// A C++ class in an Objective-C++ file.
// This C++ class would not need to sub-class ParentNotifier, and ParentNotifier
// would not be needed at all if it were not for OutsiderCPP, which talks to its 
// Objective-C parent through InsiderCPP.
class InsiderCPP : public ParentNotifie {
public:
    InsiderCPP(MyClassOCPP * parent) : myParent(parent){}            
    void doSomething() {
        callMom("To Mom from insider.");
    }
    void callMom(const char * msg) {
        [myParent notificationMethod:msg];
    }        
private:
    MyClassOCPP * __weak myParent;
};

@interface MyClassOCPP ()

@property InsiderCPP * insiderChild;
@property OutsiderCPP * outsiderChild;

@end

@implementation MyClassOCPP
-(id)init {
    self.insiderChild = new InsiderCPP(self);
    self.outsiderChild = new OutsiderCPP(self.insiderChild);            
    return self;
}        
-(void)doWork {
    self.insiderChild->doSomething();
    self.outsiderChild->doSomething();
}        
-(void)notificationMethod:(const char *)msg {
    printf("Parent has been notified with: %s\n", msg);
}
-(void)dealloc {
    delete self.insiderChild;
    delete self.outsiderChild;
}
@end

这里对应的是header,objcpp.h:

#ifndef objcpp_h
#define objcpp_h

#import <Foundation/Foundation.h>

@interface MyClassOCPP : NSObject
-(id)init;
-(void)dealloc;
-(void)doWork;
-(void)notificationMethod:(const char*)msg;
@end

#endif 

这是一个 "pure" C++ 源文件 (mylib.cpp) 与 Objective-C:

无关
#include <stdio.h>
#include "cpp.h"

void OutsiderCPP::callMom(const char * m) {
    myParent->callMom(m);
}
void OutsiderCPP::doSomething() {
    callMom("To Mom from outsider.");
}

这里是对应的header (cpp.h):

#ifndef cpp_h
#define cpp_h

class ParentNotifier
{
public:
    virtual void callMom(const char *) = 0;
};

class OutsiderCPP
{
public:
    OutsiderCPP(ParentNotifier * p) : myParent(p) {}
    void doSomething();
    void callMom(const char *);

private:
    ParentNotifier * myParent;
};

#endif 

请注意,此示例仅供参考,并非产品质量。