Skodik.o
Skodik.o

Reputation: 514

Objective-C C++ wrapper Incomplete definition of type error

Iam trying to write Objective-c wrappers for existing C++ classes. I have Objective-c header in Click.h :

#import <Foundation/Fundation.h> 
@class CClick; // forward declaration of C++ class
@interface Click : NSObject
@end

Then I have implementation of wrapper in Click.mm:

#import "CClick.h"// import of C++ 
#import "Click.h" // objc import
@interface Click ()
@property (nonatomic, readonly) CClick *clickInternal;
@end
@implementation Click
... 
- (NSString *) uri
{
const char* uri = self.clickInternal->getUri(); // here I have error with incomplete definition of type 'CClick'

CClick is my C++ class, that has just some properties and getter for them.

When I try to build my project I get: incomplete definition of type 'CClick'

getUri method definition in CClick.h in c++:

#include <string> 
#include <vector>

using namespace std;

namespace MyTest {

class CClick {

public:
    string uri;
    string id;

    string getUri() {
        return uri;
    }

    string getId() {
        return id;
    }
};

}

Upvotes: 2

Views: 1012

Answers (2)

trungduc
trungduc

Reputation: 12144

Seem like you forgot to using CClick with namespace MyTest. Check my below code.

#import <Foundation/Fundation.h>
namespace MyTest {
class CClick; // forward declaration of C++ class
}
@interface Click : NSObject
@end

Implementation file.

@interface Click ()
@property (nonatomic, readonly) MyTest::CClick *clickInternal;
@end

Or simply, add using namespace MyTest;

Important note from @Richard Hodges:

using namespace std; is a very bad idea. Using it in a header file is inviting disaster for yourself and anyone who includes your poisonous header file. You need to stop that right now.

Upvotes: 1

Arne Fischer
Arne Fischer

Reputation: 952

To write a Wrapper class you have to create a .mm class. It is unclear from your Question if your implementation is nested in a .mm class. This tells the compiler your class wants to access (or contains) c++ code. (Google Objective-C++)

Untested pseudo example. C++ Class Foo and Wrapper class Bar.

Objective C Header:

#import <Foundation/Fundation.h>     
@interface Bar : NSObject
+ (NSString *) myString;
@end

Objective C++ Implementation:

#include "Foo.h"
@implementation Bar
 + (NSString *) myString{
    return [NSString stringWithUTF8String: Foo::getMyString().c_str()];
}
@end

Pitfalls:

  • The header should not contain any C++ Code / References. Otherwise you will only be able to import it into Objective-C++ classes.
  • Type Conversions can be a pain. Always cast primitive Type conversions.

How to handle object relations and Lifecycles. E.g. when to delete your C++ Object if it is held within a Objective-C Object is a different topic, but something you should think about - this is why I used a static call in my example.

Upvotes: 0

Related Questions