有没有什么办法可以在C中使用Objective-C库?

我想用下面的代码(用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]]; 

有没有什么办法可以在c中使用objective-c库(就像在c中使用c ++库)?

基本上可以用相同的方式在C中使用C ++库

你必须提供包装C API。 如果你定义了简单的C函数,它们应该可以从另一个简单的C可执行文件轻松访问

你将需要一些头文件:

 #ifndef __OBJC__ typedef void* id; #endif id api_getlocation(); const char* api_location_to_text(id location); void api_free_location(id location); 

和代码(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]; } 

然后你可以从C代码中使用它,包括头文件和调用这些C函数。

注意 :如果你连接到objective-c运行时库,你应该也可以通过调用objc_sendMsg直接发送消息给对象,但是这将会是一个痛苦的objc_sendMsg

(1)我没有检查客观代码是否真的有意义。

你可以创build一个你需要的包装接口 – 就像他们在C ++中一样 – > C