2016-07-02 3 views
1

iOSでAudio Unit Extensionsを作成するには、C++クラスとObjective-Cクラスを混在させる必要があります。結果として、C++オブジェクトを変数の1つとして持つObjective-Cオブジェクトが作成されました。C++オブジェクトからObjective-C parentを呼び出す

私は、C++の子オブジェクトがObjective-Cの親/所有者に特定の状態変更を通知できるようにしたいと思います。擬似コードで

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

これはエレガントな方法で可能ですか?

+1

あなたのobjcオブジェクトのメンバ弱参照をあなたのcppクラスに追加してください – fnc12

+0

これは、2つのC++クラスまたはObjective-Cクラスとまったく同じ関係よりもそれほどエレガントである必要はありません。 fnc12が言ったように、これに対する通常の解決策は弱い参照です。 – zneak

答えて

0

これは、エレガントな定義方法によって異なります。これは、C++クラスがObjective-C++ファイル(拡張子が.mmのファイル)にあり、C++コードで直接使用されていない場合Objective-C++ソースファイルにありません。問題は、Objective-C++ソースファイル内にある場合のみ、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 

対応するヘッダ、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 

この例は単に例示目的のためであり、生産品質ではないことに注意してください。

関連する問題