开发者

how to return C++ pointer in objective-C++

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?


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜