4

I'm writing an Objective-C++ class interface that has to be usable from both Objective-C and Objective-C++. The problem is that, because it must be usable from Objective-C, I cannot simply use a C++ type. I want to do it using pointers and I came up with this:

@interface SXDiff : NSObject {
@private
#ifdef __cplusplus
  dtl::Diff<std::string, std::vector<std::string> > *_diff;
#else
  void *_diff;
#endif
}

...

@end

Can any problems occur when doing this? Is there a better way of doing this?


Note that the use of pointers is just to get the size of the ivar to be the same in both Objective-C and Objective-C++. The ivar can only be used from within the class implementation of SXDiff (it's @private). The implementation is written in Objective-C++.

6
  • Just curious why do you want to use obj-c? Commented Oct 18, 2011 at 14:02
  • I have an application written in Objective-C and I want to use C++ code in just one of its classes. Commented Oct 18, 2011 at 14:03
  • Which compiler are you using? With LLVM 2.0+ you can declare your dtl::Diff in the implementation file using a class extension. Commented Oct 18, 2011 at 14:07
  • @Joe I am using Apple clang version 3.0, based on LLVM 3.0svn. Commented Oct 18, 2011 at 14:08
  • Why not avoid the #ifdef altogether and just use a void*. Another option would be to wrap the c++ class into a struct and use that for hiding (pimpl idiom). Since C knows structs and pointers to structs that should work, too. Commented Oct 18, 2011 at 14:08

1 Answer 1

5

With Apple LLVM version 2.0+ try moving all of your C++ code from the header into a class extension.

//SXDiff.h
@interface SXDiff : NSObject {
}

...

@end


//SXDiff.mm
#include "dtl/dtl.hpp"

@interface SXDiff()
{
    dtl::Diff<std::string, std::vector<std::string> > *_diff;
}
@end

@implementation SXDiff

...

@end
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't know this were possible, because GCC always gave me an error when trying that. clang doesn't. Thanks! This also eliminates the need for a pointer.
BTW, an interesting new feature in the latest SDK: You can now add ivars using a {} block after @implementation rather than using a class extension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.