Making a Objective-C Wrapper for a C++ Library

后端 未结 3 476
囚心锁ツ
囚心锁ツ 2020-12-29 15:42

I am trying to make a wrapper in Objective-C so I don\'t have to write c++ outside the library classes.

The Library main file is LLAHProcessor.h .cpp

3条回答
  •  囚心锁ツ
    2020-12-29 16:06

    Your problem is that .m files are compiled as C instead of C++. Thus when the compiler comes across any C++ even in a header file while compiling a .m file, it will barf.

    No doubt you have to put some C++ in your header file because your Objective C object wraps a C++ object, but there are ways around this. One way would be to use a pointer to the C++ object and make use of the handy preprocessor define __cplusplus which is defined for C++ (and Objective-C++) but not for C (or Objective-C) e.g.

    // LLAHProcessorWrapper.h
    
    #if defined __cplusplus
    class MyCPPClass;    // forward class declaration
    #else
    typedef struct MyCPPClass MyCPPClass;   // forward struct declaration
    #endif
    
    @interface MyOCClass : NSObject
    {
    @private
        MyCPPClass* cppObject;
    } 
    
    // methods and properties
    
    @end
    

    Since you never dereference the members of the cppObject outside of the .mm file it doesn't matter that you never provide a full definition for the struct.

    You would new and delete the pointer in -init and -dealloc respectively. You would include the full C++ class declaration in LLAHProcessorWrapper.mm.

提交回复
热议问题