从 C 调用 Cocoa API [英] Calling Cocoa APIs from C

查看:29
本文介绍了从 C 调用 Cocoa API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是否可行,但是使用纯 C 语言编写代码,是否可以从中调用 Cocoa API?
#include 之类的,添加对应的库就可以了?

I don't know if this is possible, but having code in plain C, is it possible to call Cocoa API's from it?
Something like #include <cocoa.h>, add the corresponding library and go for it?

感谢您的帮助

推荐答案

如果链接到 Cocoa 或 Foundation 框架,则可以在 C 代码中使用 Objective-c.但是,如果您想使用正常的消息传递语法,则必须将文件扩展名从 .c 更改为 .m,以便将其编译为 Objective-c.如果您保留 .c 扩展名,您将只能使用 c 样式的运行时调用与目标对象(即 objc_msgSendobjc_getClass 等)进行交互.

If you link against the Cocoa or Foundation frameworks, you can use objective-c within your C code. However, if you want to use the normal messaging syntax, you will have to change the file extension from .c to .m so that it is compiled as objective-c. If you keep the .c extension, you will only be able to use the c-style runtime calls to interact with objective-objects (i.e. objc_msgSend, objc_getClass, etc.).

示例:在 .m 文件中

Examples: Within a .m file

void cFunction() {
    [[NSString alloc] init];
}

在 .c 文件中

void cFunction() {
    void* cls = objc_getClass("NSString");
    void* obj = objc_msgSend(cls, NSSelectorFromString(CFSTR("alloc")));
    obj = objc_msgSend(obj, NSSelectorFromString(CFSTR("init")));
}

如果选择第二种方法,请参见Objective-C 运行时参考.

If you choose the second method, see the Objective-C Runtime Reference.

这篇关于从 C 调用 Cocoa API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆