views:

44

answers:

2

Hi. Is it possible to have a objective c member in a c++ class

@interface ObjectiveCClass : UIViewController  {

    int someVarialbe;

}
- (void)someFunction;

@end


class CPlusPlusClass{
      ObjectiveCClass obj;          // have a objective c member

      void doSomething(){
           obj.someFunction;        // and call a objective c method
       }
};

Any guidance would really be appreciated.

Cheers

+1  A: 

To create header files that can be shared between obj-c and cpp code, you could use the compiler predefined macros to do something like:

// A .h file defining a objc class and a paired cpp class
// The implementation for both the objective C class and CPP class
// MUST be in a paired .mm file
#pragma once

#ifdef __OBJC__
#import <CoreFoundation/CoreFoundation.h>
#else
#include <objc/objc.h>
#endif

#ifdef __OBJC__

@interface ObjectiveCClass :
...

typedef ObjectiveCClass* ObjectiveCClassRef;

#else

typedef id ObjectiveCClassRef;

#endif

#ifdef __cplusplus

class CPlusPlusClass {
  ObjectiveCClassRef obj;

  void doSomethind();
};

#endif

Im not 100% sure its legal to have ObjectiveCClassRef change type like that between c/cpp and obj-c builds. But id is a c/cpp compatible type defined in the objective C header files as capable of storing an objective C class pointer, and, when used in .m or .mm files, allows you to call the object directly using objective C syntax.

Chris Becke
When i add the #include "ObjectiveCClass.h" to the c++ file i get 9000 errors, like:Expected unqualified-id before '-' tokenandStray '@' in program
Header Files that are going to be shared between .cc / .cpp and /mm files need to be sanitized. You can't use any of objective-Cs @ directives in such a header file.
Chris Becke
So what does a objective-c class have to look like so i can have a member of it in a c++ class. Thanks for your help.
You are a hell man. Ill give it a shot. Thank you.
i hope thats a compilment :P its rare one gets to see objective-c / cpp interop questions.
Chris Becke
So that compiles but how do i go about accessing CPlusPlusClass from another c++ class. I still have to #include the "ObjectiveCClass.h", which throws all those errors. Edit. Turn all the .cpp to .mm should sort it out
You don't need to convert all the cpp to mm. the macro's should take care of things and let you #include the cppc.h from cpp or mm files.
Chris Becke
A: 

There's a dialect of Objective-C called Objective-C++ that is interoperable with C++ the same way that Objective-C is interoperable with C. You can either change the setting for the file to be Objective-C++ or change the extension to ".mm". You'll still need to access Objective-C objects through pointers and do the alloc-init dance and all that, of course.

Chuck