C++ Callbacks with objective-C, an application to RtMidi

后端 未结 1 1847
日久生厌
日久生厌 2021-01-07 08:52

I\'ve read several of the previous discussion about the subject but since I\'m relatively new to Objective-C, I don\'t really understand them. (Blocks, selectors, and delega

1条回答
  •  -上瘾入骨i
    2021-01-07 09:35

    It's possible to have C++ and Objective-C within the same project and even within the same file (Objective-C++ with file extension .mm). If the code you're using is designed for a C++ callback, it may be easier to provide that and communicate between different object types outside of that mechanism.


    //  CPPClass.h
    
    #ifndef CPPClass_h
    #define CPPClass_h
    
    class CPPClass {
    private:
        id m_ocObject;
    
    public:
        CPPClass(id ocObject);
        virtual ~CPPClass();
    
        void verifyCPP();
    
    };
    
    #endif
    

    //  OCClass.h
    
    #import 
    
    class CPPClass;
    
    @interface OCClass : NSObject {
        CPPClass *cppObject;
    }
    
    - (void)ocCallback;
    - (void)verifyOC;
    
    @end
    

    //  OCClass.mm
    
    #import "OCClass.h"
    #import "CPPClass.h"
    
    #include 
    
    @implementation OCClass
    
    - (id)init {
        self = [super init];
        if (self) {
            cppObject = new CPPClass(self);
        }
        return self;
    }
    
    - (void)dealloc {
        delete cppObject;
    }
    
    - (void)ocCallback {
        NSLog(@"Objective-C called from C++");
    }
    
    - (void)verifyOC {
        NSLog(@"Objective-C called from Objective-C");
        cppObject->verifyCPP();
    }
    
    @end
    
    CPPClass::CPPClass(id ocObject) : m_ocObject(ocObject)
    {}
    
    CPPClass::~CPPClass() {}
    
    void CPPClass::verifyCPP() {
        std::cout << "C++ called from Objective-C" << std::endl;
        [m_ocObject ocCallback];
    }
    

    To activate this, some other .mm file would have:

    #import "OCClass.h"
    ...
    OCClass *test = [[OCClass alloc] init];
    [test verifyOC];
    

    0 讨论(0)
提交回复
热议问题