Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping Objective C in Objective c++/c++

Tags:

c++

xcode

macos

I've got a c++ app written using Boost/WXWidgets, targeting Windows and Mac OSX. However, I've got one issue that I can't solve using these libraries. My solution requires me to wrap an Objective C class so that I can call it from one of my c++ modules. My research so far tells me that I need to use Objective C++ written into source files with a .mm extension, allowing XCode to treat the file as a mix of Objective C and c++. I've found lots of articles detailing how to wrap c++ so that it can be called from ObjectiveC, but nothing that gives any detail on the reverse. Any links to articles or, better still, a worked example, would be greatly appreciated.

like image 521
Tim Burgess Avatar asked Aug 20 '11 15:08

Tim Burgess


2 Answers

If you want a reusable pure C++ wrapper around an Objective C class, the Pimpl idiom works pretty well. The Pimpl idiom will make it so that there is no Objective C / Cocoa stuff visible in the header file that will be included by pure C++ code.

// FooWrapper.hpp

// Absolutely no Cocoa includes or types here!

class FooWrapper
{
public:
    int bar();

private:
    struct Impl; // Forward declaration
    Impl* impl;
};


// FooWrapper.mm

@import "FooWraper.hpp"
@import "Foundation/NSFoo.h"

struct FooWrapper::Impl
{
    NSFoo* nsFoo;
};

FooWrapper::FooWrapper() : impl(new Impl)
{
    impl->nsFoo = [[NSFoo alloc] init];
}

FooWrapper::~FooWrapper()
{
    [impl->nsFoo release];
    delete impl;
}

int FooWrapper::bar()
{
    return [impl->nsFoo getInteger];
}
like image 52
Emile Cormier Avatar answered Oct 04 '22 21:10

Emile Cormier


Just mix it (but don't forget setting up the pool). It works.

 // obj-c code, in .mm file
 void functionContainingObjC(){
        NSAutoreleasePool*pool=[[NSAutoreleasePool alloc] init]; 
        [lots of brackets!];
        [pool release];
 }

 // c++ code, in .cc file
 functionContainingObjC();
like image 33
Yuji Avatar answered Oct 04 '22 20:10

Yuji