在Xcode项目中,我有一个带有函数的C文件,它编译并运行正常
我想在struct(s)中包装我的C代码,我将如何在Objective-C中调用它们?
答案 0 :(得分:57)
Objective-C是C的正确超集。您在C中可以做的任何事情都可以在Objective-C中完成。所以,你真的不需要将它们视为不同的语言; Objective-C只是“C加上一些东西”。
// this struct is compatible with C and Obj-C
struct fruit {
int a;
};
int main()
{
struct fruit apple;
apple.a = 1;
return 0;
}
然后,任何C或Objective-C源文件都可以访问该结构。 Objective-C没有引入任何其他复杂情况。
答案 1 :(得分:48)
声明函数指针,将它们添加到您的结构然后调用它们,它只是C。
示例:
//Typedef 2 function pointers, first takes and returns int,
// second takes and returns double
typedef int (*FuncPtrInt) (int);
typedef double (*FuncPtrDouble)(double);
// create structure to store function pointers
struct ABC
{
FuncPtrInt applyA;
FuncPtrDouble applyB;
};
// create some functions to use with structure
int incrFuncA(int num) { return ++num; }
double decrFuncB(double num) { return --num; }
double multiplyFuncB(double num) { return num*num; }
// try it out
void testStruct()
{
struct ABC abc;
abc.applyA = incrFuncA;
abc.applyB = decrFuncB;
NSLog(@"increment: %d",abc.applyA(3));
NSLog(@"decrement: %f",abc.applyB(3.5));
abc.applyB = multiplyFuncB;
NSLog(@"multiply: %f",abc.applyB(3.5));
}
输出:
2010-02-01 10:36:22.335 x[11847] increment: 4
2010-02-01 10:36:22.336 x[11847] decrement: 2.500000
2010-02-01 10:36:22.336 x[11847] multiply: 12.250000
如果你想拥有一个带有函数的结构,其中函数在结构上运行,你必须默认将指针传递给该函数(类似于c ++的作用):
定义:
struct ClassABC;
typedef int (*FuncPtrClassABC)(struct ClassABC *);
typedef int (*FuncPtrClassABCInt)(struct ClassABC *, int);
int incrFunc(struct ClassABC * abc);
int decrFunc(struct ClassABC * abc);
int addFunc(struct ClassABC * abc, int num);
int subtractFunc(struct ClassABC * abc, int num);
struct ClassABC
{
int i;
FuncPtrClassABC increment;
FuncPtrClassABC decrement;
FuncPtrClassABCInt add;
FuncPtrClassABCInt subtract;
};
正如您所看到的,这些函数可以是独立的,您仍然可以传递ClassABC:
int incrFunc(struct ClassABC * abc) { return ++(abc->i); }
int decrFunc(struct ClassABC * abc) { return --(abc->i); }
int addFunc(struct ClassABC * abc, int num)
{ abc->i += num; return abc->i; }
int subtractFunc(struct ClassABC * abc, int num)
{ abc->i -= num; return abc->i; }
初始化助手功能:
void initClassABC(struct ClassABC * abc)
{
abc->i = 0;
abc->increment = incrFunc;
abc->decrement = decrFunc;
abc->add = addFunc;
abc->subtract = subtractFunc;
}
用法:
struct ClassABC cabc;
initClassABC(&cabc);
cabc.add(&cabc,4);
NSLog(@"add: %d", cabc.i);
cabc.decrement(&cabc);
NSLog(@"decrement: %d", cabc.i);
cabc.subtract(&cabc,2);
NSLog(@"subtract: %d", cabc.i);
输出:
2010-02-01 10:56:39.569 x[12894] add: 4
2010-02-01 10:56:39.569 x[12894] decrement: 3
2010-02-01 10:56:39.569 x[12894] subtract: 1
享受