简体   繁体   English

是否可以像在C语言中一样在ObjC中使用函数和函数指针?

[英]Can functions and function pointers be used in ObjC just as they are in C?

I am familiar with C and am now learning Objective-C. 我熟悉C,现在正在学习Objective-C。

I often use function pointers 我经常使用函数指针

void (*callback)(int*restrict, char*restrict)

Will that be usable in Objective-C? 可以在Objective-C中使用吗? Especially in structs, like so: 尤其是在结构中,如下所示:

struct mytype myvar = {
    .first = myCallback;
    .second = myCallback2;
} 

Also, I wish to have function prototypes like 另外,我希望有类似的功能原型

void function(int * restrict a, char * restrict b);
char * function (char * a);
...

Are there no problems with using this style? 使用这种样式没有问题吗?

Clang (the default compiler used by Xcode) claims C11 support for Objective C (See Language Compatibility ). Clang(Xcode使用的默认编译器)声称对目标C的C11支持(请参阅语言兼容性 )。

This means function pointers, restrict, structs, and declarations will all work as you would expect. 这意味着函数指针,限制,结构和声明都将按您期望的那样工作。

One word of advice: don't fight the system; 一个建议:不要与系统抗争; it will create more work for yourself and less reliable software for your users. 它将为您自己创造更多的工作,而为您的用户带来不可靠的软件。 Programmers should be like water. 程序员应该像水一样。

Empty your mind, be formless, shapeless — like water. 放空您的思想,变得无形,无形-像水一样。 Now you put water in a cup, it becomes the cup; 现在,您将水倒入杯子中,它变成杯子了。 You put water into a bottle it becomes the bottle; 你把水倒进瓶子里就变成瓶子了。 You put it in a teapot it becomes the teapot. 您将其放入茶壶中,便成为茶壶。 Now water can flow or it can crash. 现在,水可以流动或崩溃。 Be water, my friend. 是水,我的朋友。

Bruce Lee 李小龙

Yes. 是。

You can use any C strategy that you choose in your Objective-C app. 您可以使用在Objective-C应用程序中选择的任何C策略。 You will still have to write some Objective-C in order to start your UIApplication (or use a third-party tool to do it for you). 您仍然必须编写一些Objective-C才能启动UIApplication (或使用第三方工具为您完成)。

One thing to keep in mind, though, is that int will be a different length depending on the machine and you should explicitly choose int32_t or int16_t or int8_t if you really don't want to use the NSInteger typedef that abstracts this machine difference. 不过要记住的一件事是, int长度取决于计算机, int8_t如果您真的不想使用抽象化此计算机差异的NSInteger typedef ,则应显式选择int32_tint16_tint8_t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM