views:

118

answers:

1

I am using the iphone SDK and coding primarily in C++ while using parts of the SDK in obj-c. Is it possible to designate a C++ class in situations where an obj-c class is needed? For instance:

1) when setting delegates to obj-c objects.

  • I cannot make a C++ class derive from a Delegate protocol so this and possibly other reasons prevent me from making my C++ class a delegate for various obj-c objects. What I do as a solution is create an obj-c adapter class that contains a ptr to the C++ class and is used as the delegate (notifying the C++ class when it is called). It feels cumbersome to write these every time I need to get delegate notifications to a C++ class.

2) when setting selectors

  • This goes hand in hand with item 1. Say I want to set a callback to fire when something is done, like a button press or a setAnimationDidStopSelector in the UIView animation functionality. It would be nice to be able to designate a C++ function along with the relevant delegate for setAnimationDelegate.

Well, I suspect this isn't readily possible, but if anyone has any suggestions on how to do it if it is, or on how to write such things more easily, I would love to hear them. Thanks.

+1  A: 

The sad news is that you can't get completely around the adapters, but you can ease the job. By using the Objective-C runtime libraries you can reduce the clutter by generating the adapters for you with a declarative approach.

The Objective-C runtime allows you to construct classes at runtime for which you can set the implementation function for the methods. Using templates, you can thus generate an Objective-C class from a type-oriented declaration by generating the trampoline functions that invoke the C++ methods that you want.

I started a prototype a while back and the state mentioned there might be sufficient in your case. It is possible to do this better and support properties and Distributed Objects cleanly too, but i haven't found the time yet to implement a better version.

Georg Fritzsche