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

Calling Objective-C parent from C++ object

本文关键字:对象 Objective-C 调用 c++      更新时间:2023-10-16

在iOS上创建音频单元扩展需要混合使用c++和Objective-C类。因此,我现在有了一个Objective-C对象,其中一个变量是c++对象。

我希望c++子对象能够在某些状态变化时通知它的Objective-C父/所有者。

在伪代码:

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

这是否可能以一种优雅的方式实现?

这取决于你如何定义优雅…如果c++类位于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: %sn", msg);
}
-(void)dealloc {
    delete self.insiderChild;
    delete self.outsiderChild;
}
@end

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 

这是一个"纯"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.");
}

,这里是相应的标头(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 

请注意,这个例子只是为了说明目的,而不是生产质量。