views:

207

answers:

3

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

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

I have created the simple method

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

Everything seems to work until I actually try to use the object in another file

newObj = [createdMyObj getObj];

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

It seems that the method is 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 that?

+2  A: 

On my 10.6.3 machine, the following combination worked without any problem: 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 might have fallen into:

  1. Unlike C++, a class in Objective-C which doesn't inherit from NSObject won't work. (Well, you can make it work, but you don't want that usually.) Note the line @interface MyObj:NSObject.
  2. To use NSObject, do #import <Foundation/Foundation.h>
  3. Don't forget to use the extension .mm for Objective-C++ files.
Yuji
+1  A: 

Most likely you have forgotten to #import the header file with the @interface into the .mm file where you use getObj.

JeremyP
+1  A: 

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

Michael Tindal