【发布时间】:2012-10-12 07:25:12
【问题描述】:
我的 viewController.m 中有一个 c 函数。
int abc(int a, char* b)
{
//do something
}
我还有一个功能
-(void) callIncomingClass
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//set the position of the button
button.frame = CGRectMake(100, 170, 100, 30);
//set the button's title
[button setTitle:@"Click Me!" forState:UIControlStateNormal];
//add the button to the view
[self.view addSubview:button];
}
现在我想从函数 abc 中调用 callIncomingClass。
你建议我怎么做??
我为什么要从 C 函数调用一个 Objective C 方法是,我不能在 C 函数中创建一个按钮或做一些类似的处理。
以下代码是否有效:
int abc(int a, char* b)
{
ViewController * tempObj = [[ViewController alloc] init];
[tempObj callIncomingClass];
}
编辑:我在做什么的大图景 有一个 c 库,即 library.c 和 library.h 文件。 library.h 文件有一个具有回调函数的结构。这些需要分配函数指针。所以我有一个带有签名 int abc(int,char*) 的 c 函数,它要分配给结构中的回调函数。
这个函数 abc 在 ViewController.m 中定义。 理想情况下,我希望它在单独的文件中定义。但这也没关系。
所以现在,回调事件发生了,我想在视图上创建一个带有一些操作的 UIButton。由于我无法从 c 函数创建 UIButton,因此我正在调用 ViewController 类的目标 C 方法,该方法创建 UIButton。
希望能清楚地说明我打算如何使用它。
【问题讨论】:
-
你可以这样做......但你需要参考
self。 c函数不是对象的一部分..所以它不知道self是什么。 -
您能说得更具体一点吗?我可以做2中的哪一个??从 C 函数调用目标 c 函数?还是从 C 函数创建 UIButton??
-
如果您有一个现有的
ViewController实例,那将创建一个全新的实例,这可能不是您想要的。请笼统地描述您要完成的工作。如果abc()是一个不能改变签名的回调函数,它在哪里定义,它有什么作用?ViewController实例是设置回调函数的对象吗? -
有时当您将 c 函数作为回调时,它会为您提供
void*参数以将您自己的数据传递到您的实现中。为什么这里不是这种情况/C 库是做什么的?否则解决这个问题的唯一方法是使用全局变量(这几乎不是答案。)
标签: objective-c c cocoa-touch function