我想使用下面的 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
直接向对象发送消息,但这将证明成为......的痛苦
(1) 我没有检查 objective-c 代码是否真的有意义。
关于iphone - 有没有办法在 C 中使用 Objective-C 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8945028/