Cintu
Cintu

Reputation: 913

Calling Objective C++ methods from Objective C Classes

Is it possible to Call the Objective- C++ classes and methods from the Objective C Class?

Already we have written a project with Objective C code. Now we have one C++ class to be integrated, So i thought to change only one Class to Objective C++ which interacts with native C++ Classes others will remain in Objective C. Is it possible? Could anyone can help me for better solution?

Thanks.

Upvotes: 1

Views: 207

Answers (3)

uliwitness
uliwitness

Reputation: 8843

Yes, as long as you restrict your use of C++ types to the implementation file, you can call all of your ObjC++ classes from regular Objective C. There are a few gotchas, like wrapping any "loose" functions that you import in 'extern "C"' (like you would do when mixing C++ and straight C), but if you can assume a moderately recent version of Xcode (and don't need support for 32-bit MacOS), you can easily do all of that with a class extension (aka "class continuation").

If you want some tips and tricks about that topic, I was a guest on an episode of NSBrief a while ago where I talked at length about pretty much every aspect of using ObjC++: http://nsbrief.com/113-uli-kusterer/

You may also find an answer on this similar question: Can I separate C++ main function and classes from Objective-C and/or C routines at compile and link?

Upvotes: 1

Cy-4AH
Cy-4AH

Reputation: 4605

Yes. It's possible. Just hide C++ fields in extension. There is example:

//.h-file
@interface IntVector: NSObject

- (int) valueAtIndex:(NSUInteger) idx;
- (NSUInteger) size;
- (void) insertValue:(int) val atIndex:(NSUInteger) idx;

@end

//.mm-file
#include <vector>
using namespace std;

@interface IntVector()
{
    vector<int> _vals;
}
@end

@implementation IntVector

- (int) valueAtIndex:(NSUInteger)idx
{
    return _vals[idx];
}

- (NSUInteger) size
{
    return _vals.size();
}

- (void) insertValue:(int) val atIndex:(NSUInteger) idx
{
    _vals.indest(_vals.begin()+idx, val);
}

@end

You will be able use this class with any other objective-c code.

Upvotes: 1

Chuck
Chuck

Reputation: 237110

Yes, you can do that. As long as the interface of the class is C-ish, Objective-C doesn't care if the implementation is Objective-C or Objective-C++.

Upvotes: 2

Related Questions