使用C结构目标C [英] Use C Struct in Objective C
本文介绍了使用C结构目标C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在一个X code项目,我有功能的C文件,它编译和作品确定
In an Xcode project I have a C file with functions, it compiles and works OK
我要包我的C code在结构上,我怎么能叫他们在Objective-C?
I want to wrap my C code in struct(s), how will I be able to call them in Objective-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 ++一样):
If you want to have a struct with functions where functions operate on the structure you have to pass the pointer to that function by default (similar to what c++ does):
定义:
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的:
As you can see these functions could be standalone, you would still pass the ClassABC in:
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; }
初始化帮手FUNC:
Initialization helper func:
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
欣赏
这篇关于使用C结构目标C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文