Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C member in C++ class

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

like image 661
user346443 Avatar asked Jan 22 '23 05:01

user346443


1 Answers

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.

like image 157
Chris Becke Avatar answered Jan 31 '23 12:01

Chris Becke