1

I've been digging into Apple's example code related to MapKit and specifically overlays. I've noticed that large parts of the code, namely the sections that need to be as performant as possible, are written as C functions. If I want to share such functions between classes what are my options? Obviously I can't declare them as class methods and share the class, so what is the best way to allow multiple classes access to the same C functions?

japreiss
  • 11,111
  • 2
  • 40
  • 77
Undistraction
  • 42,754
  • 56
  • 195
  • 331
  • Does this related post help? http://stackoverflow.com/questions/801976/mixing-c-functions-in-an-objective-c-class – TJD Dec 01 '11 at 20:02

2 Answers2

2

Objective C is a superset of ANSI C. As such, all C functions are automatically global, shared everywhere, and callable from anywhere, unless specifically declared static. This is true even if the C function is instantiated inside an Objective C class implementation.

Just put an extern declaration, such as:

extern myType my_C_function(parameterType foo);

in the .h header file of any Objective C class from which you want to call your (non static) C function.

hotpaw2
  • 70,107
  • 14
  • 90
  • 153
  • Thanks for replying. Is there any performance difference between declaring a function in the class that uses it and declaring it in a separate header? – Undistraction Dec 01 '11 at 21:31
1

Reentrancy is key. Make sure you do not use any share data other that constant references in your C functions. Also if a reference to an objective-C class is needed for callbacks, then that can be passed as a void pointer.

Joe
  • 56,979
  • 9
  • 128
  • 135