我在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类的Objective-C方法来创建UIButton。
希望这能清楚地说明我计划如何使用它。
self
的引用。C 函数不是对象的一部分,因此它不知道self
是什么。 - BastianViewController
实例,那么它将创建一个全新的实例,这可能不是您想要的。请广泛描述您要完成的任务。如果abc()
是一个回调函数,其签名无法更改,那么它在哪里定义,它是做什么的?ViewController
实例是否是设置回调函数的对象? - NSGodvoid*
参数,以便在你的实现中传递自己的数据。但是这里为什么不是这种情况呢?C库做了什么?否则,唯一的解决方法就是使用全局变量(这几乎永远不是答案)。 - tehwalrus