How to return a C ++ pointer in objective-C ++

I have the following objective-C ++ header with a simple method to return this pointer.

@interface MyObj
{
  MyCPPObj * cpp;
}
-(MyCPPObj *) getObj;

      

I created a simple method

@implementation MyObj
-(MyCPPObj *) getObj
{
  return cpp;
}

      

Everything works until I try to use the object in another file

newObj = [createdMyObj getObj];

      

It complains: error: cannot convert 'objc_object *' to 'MyCPPObje *' on initialization.

The method seems to return an objective-c object, but I specifically requested a C ++ pointer.

MyCPPObj is an honest C ++ class:

class MyCPPObj
{
 public:
   int x;
}

      

How can I fix this?

+2


a source to share


3 answers


Most likely you forgot the #import

c header file @interface

in the .mm file where you are using getObj

.



+1


a source


On my 10.6.3 computer, the following combination worked without problems: aho.h

#import <Foundation/Foundation.h>
class MyCPPObj{
};
@interface MyObj:NSObject
{
  MyCPPObj * cpp;
}
-(MyCPPObj *) getObj;
@end

      

and aho.mm



#import <Foundation/Foundation.h>
#import "aho.h"

void foo(){
    MyObj*objcObj=[[MyObj alloc] init];
    MyCPPObj*cppObj=[objcObj getObj];
}

      

Two pitfalls you may have fallen into:

  • Unlike C ++, a class in Objective-C that does not inherit from NSObject

    will not work. (Well, you can get it to work, but you usually don't need to). Pay attention to the line @interface MyObj:NSObject

    .
  • To use NSObject

    , run#import <Foundation/Foundation.h>

  • Remember to use the .mm

    Objective-C ++ file extension .
+3


a source


The error tells what is going on and JeremyP is right for the money. When you forget to include the selector prototype header file, the compiler assumes that the selector returns an object of type id. Well id is a typedef for objc_object *, which is incompatible with your C ++ class. To fix the error, you just need to include your header file in the file where you called getObj.

+1


a source







All Articles