Porting C++ code to Objective-C

Porting C++ code to Objective-C

I’m in the middle of porting a Windows C++ application to the mac.  I’ve posted before that I was pleasantly pleased to find that with some limitations, XCode supports mixing C++ and objective-C code.

Here are a few things to look out for when working with C++ code in a Cocoa application:

1. Missing C++ member functions may not be flagged at compile time and your program will abort with a message similar to:

ZeroLink: unknown symbol ‘__ZN8DVFArray6ExistsEP6DVFObj’

You can use the C++filt program which is part of the GNU Binary Utilities to help demangle the function in error.  I could not build this package so I looked and found a copy of the C++filt program. Unfortunately I could only find a copy for the PC.
The example listed demangles to: DVFArray::Exists(DVFObj*)

2. You cannot store C++ objects/pointers in Cocoa containers.  One workaround is to store NSValue objects in the containers and store C++ pointeres in the NSValue objects:

[myNSArray addObject:[NSValue valueWithPointer:pCPPObj]];
.
.
pCPPObj = [[_array objectAtIndex:idx] pointerValue]

3. You should not use static C++ objects or static data members.  Constructors for static objects will be called before main() is called and you will not have an NSAutoReleasePool initialized yet. You will get a message similar to:

*** _NSAutoreleaseNoPool(): Object 0x307f60 of class NSConcreteValue autoreleased with no pool in place – just leaking

The discussion "NSAutoreleasePool and static data member constructors" is very good on this subject

One thought on “Porting C++ code to Objective-C

Leave a Reply