有什么方法可以在C中使用Objective-C库? [英] is there any way to use Objective-C library in C?
问题描述
我想使用C中的以下代码(使用arm-gcc编译)
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]];
有什么方法可以在c中使用Objective-c库(例如在c中使用c ++库)?
Is there any way to use objective-c library in c (like using c++ library in c)?
推荐答案
基本上可以使用与在C语言中使用C ++库相同的方式.
It is possible basically in the same manner you would use C++ library in C.
您必须提供包装C API.如果定义普通C函数,则应该可以从另一个普通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.
您将需要一些头文件:
#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函数.
Then you could use it from C code, including your header file and calling these C function.
NB :如果您与Objective-C运行时库链接,则还应该能够通过调用objc_sendMsg
直接向对象发送消息,但这在中会很麻烦. ...
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)我没有检查Objective-C代码是否真的有意义.
(1) I have not checked if the objective-c code actually makes sense.
这篇关于有什么方法可以在C中使用Objective-C库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!