Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the pitfalls and gotchas of mixing Objective-C and C?

Tags:

c

objective-c

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.

like image 945
gargantuan Avatar asked Apr 03 '09 19:04

gargantuan


3 Answers

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!

like image 116
Jarret Hardie Avatar answered Nov 09 '22 09:11

Jarret Hardie


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

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

like image 35
Keith Gaughan Avatar answered Nov 09 '22 11:11

Keith Gaughan


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.

like image 28
Varkhan Avatar answered Nov 09 '22 09:11

Varkhan