What is up.
RSS icon Email icon Home icon
  • Porting C++ code to Objective-C

    Posted on March 20th, 2008 Alan 1 comment

    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 response to “Porting C++ code to Objective-C”

    1. Funnily enough, I found your blog because I was trying to figure out why breakpoints in Xcode stopped working (the lazy symbol loading thing did the trick!) and then I found this entry. It’s similar to something I posted just earlier today on my blog about calling ObjC from my C++ code… http://www.screwtheman.com/2008/05/an_idea_objc_and_ccollide.html

      Good luck!

    Leave a reply

    You must be logged in to post a comment.