函数和函数指针可以像在 C 中一样在 ObjC 中使用吗?
Can functions and function pointers be used in ObjC just as they are in C?
我熟悉C,现在正在学习Objective-C。
我经常使用函数指针
void (*callback)(int*restrict, char*restrict)
在 Objective-C 中可以使用吗?特别是在结构中,像这样:
struct mytype myvar = {
.first = myCallback;
.second = myCallback2;
}
另外,我希望有像
这样的函数原型
void function(int * restrict a, char * restrict b);
char * function (char * a);
...
使用这种风格没有问题吗?
是。
您可以在 Objective-C 应用中使用您选择的任何 C 策略。您仍然需要编写一些 Objective-C 才能开始您的 UIApplication
(或使用第三方工具为您完成)。
不过要记住的一件事是,int
的长度因机器而异,您应该明确选择 int32_t
或 int16_t
或 int8_t
如果你真的不想使用NSInteger
typedef
抽象出这台机器的区别。
Clang(Xcode 使用的默认编译器)声称 C11 支持 Objective C(参见 Language Compatibility)。
这意味着函数指针、限制、结构和声明都将按照您的预期工作。
忠告一句话:不要和系统作对;它将为您自己创造更多工作,并为您的用户创造更不可靠的软件。程序员要像水一样。
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.
我熟悉C,现在正在学习Objective-C。
我经常使用函数指针
void (*callback)(int*restrict, char*restrict)
在 Objective-C 中可以使用吗?特别是在结构中,像这样:
struct mytype myvar = {
.first = myCallback;
.second = myCallback2;
}
另外,我希望有像
这样的函数原型void function(int * restrict a, char * restrict b);
char * function (char * a);
...
使用这种风格没有问题吗?
是。
您可以在 Objective-C 应用中使用您选择的任何 C 策略。您仍然需要编写一些 Objective-C 才能开始您的 UIApplication
(或使用第三方工具为您完成)。
不过要记住的一件事是,int
的长度因机器而异,您应该明确选择 int32_t
或 int16_t
或 int8_t
如果你真的不想使用NSInteger
typedef
抽象出这台机器的区别。
Clang(Xcode 使用的默认编译器)声称 C11 支持 Objective C(参见 Language Compatibility)。
这意味着函数指针、限制、结构和声明都将按照您的预期工作。
忠告一句话:不要和系统作对;它将为您自己创造更多工作,并为您的用户创造更不可靠的软件。程序员要像水一样。
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.