tags:

views:

511

answers:

4

At the risk of oversimplifying something I'm worried might be ridiculously complex, what should I be aware of when mixing C and Objective-C?

Edit: Just to clarify, I've never worked with C before, and I'm learning Objective-C through Cocoa. Also I'm using the Chipmunk Dynamics engine, which is C.

+6  A: 

You can't 'mix' C and Objective-C: Objective-C is a superset of C.

Now, C++ and Objective-C on the other hand...

Keith Gaughan
how should I reword the question?
gargantaun
It's not a matter of rewording. Objective-C contains all of C, so there's no mixing at all.
Daniel Lew
I get you, but bear in mind I'm new to C in any flavour, and learning cocoa focusses on Objective-C. However, Chipmunk is written in pure C. So, I've already come across an issue where Structs are not Objects, even though to a new guy, the look the same at first.
gargantaun
Suppose you have something in C that you want to use, and want to hook it into an Objective-C framework.
David Thornley
A: 

Objective-C used to be a superset of ANSI C (ie: can't conflict). I assume that's still the case.

Dinah
+8  A: 

I'd put it the other way around: you might be risking overcomplicating something that is ridiculously simple :-)

Ok, I'm being a bit glib. As others are pointing out, Objective-C is really just a minimal set of language extensions to C. When you are writing Objective-C code, you are actually writing C. You can even access the internal machinations of the Objective-C runtime support using some handy C functions that are part of the language (no... I don't recommend you actually DO this unless you really know what you're doing).

About the only time I've ever had mildly tricky moments is when I wanted to pass an Objective-C instance method as a callback to a C function. Say, for example, I'm using a pure-C cross platform library that has functions which accept a callback. I might call the function from within an object instance to process some data, and then want that C function to call my instance BACK when its done, or as part of getting additional input etc etc (a common paradigm in C). This can be done with funky function wrapping, and some other creative methods I've seen, and if you ever need to do it googling "objective-c method for c callback" or something like that will give you the goods.

The only other word of advice is to make sure your objects appropriately manage any manually malloced memory that they create for use by C functions. You'll want your objective-c classes to tidy up that memory on dealloc if, indeed, it is finished.

Other than that, dust off any reference on C and have fun!

Jarret Hardie
+1  A: 

Objective C is a superset of C, so it shouldn't conflict.

Except that, as pointed here pure C has different conventions (obviously, since there is no built-in mechanism) to handle OO programming. In C, an object is simply a (struct *) with function pointers.

Varkhan