Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any way to use Objective-C library in C?

I want to use the below code from C (compile with arm-gcc)

NSString *newText;

CLLocationManager * locationManager = [[CLLocationManager alloc] init];
[locationManager startUpdatingLocation];
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
//[locationManager setDelegate:self];

CLLocation* location = [locationManager location];

newText = [[NSString alloc] initWithFormat: @"Your Position : %f %f", [location horizontalAccuracy], [location verticalAccuracy]];

Is there any way to use objective-c library in c (like using c++ library in c)?

like image 565
osmund sadler Avatar asked Jan 20 '12 16:01

osmund sadler


1 Answers

It is possible basically in the same manner you would use C++ library in C.

You have to provide the wrapping C API. If you define plain C functions, they should be easily accessible from another plain C executable.

You will need some header file:

#ifndef __OBJC__
typedef void* id;
#endif

id api_getlocation();
const char* api_location_to_text(id location);
void api_free_location(id location);

And the code (1):

id api_getlocation()
{
  CLLocationManager * locationManager = [[CLLocationManager alloc] init];  
  [locationManager startUpdatingLocation];
  [locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
   //[locationManager setDelegate:self];

   CLLocation* location = [locationManager location];
   return [location retain];
}

const char* api_location_to_text(id location) 
{
   NSString* newText = [NSString stringWithFormat: @"Your Position : %f %f", [location horizontalAccuracy], [location verticalAccuracy]];

   return strdup([newText UTF8String]);
}

void api_free_location(id location)
{
    [location release];
}

Then you could use it from C code, including your header file and calling these C function.

NB: if you link with objective-c runtime library, you should be also able to directly send messages to the objects by calling objc_sendMsg, but this will prove to be a pain in ....

(1) I have not checked if the objective-c code actually makes sense.

like image 112
Krizz Avatar answered Oct 12 '22 23:10

Krizz