C函数调用目标C函数

我在viewController.m中使用了ac函数。

int abc(int a, char* b) { //do something } 

我也有一个function

 -(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]; } 

编辑:我正在做的大事有一个ac库,即一个library.c和library.h文件。 library.h文件有一个具有回调函数的结构。 这些需要分配函数指针。 所以我使用签名int abc(int,char *)的ac函数将被分配给struct中的回调函数。

此函数abc在ViewController.m中定义。 理想情况下,我希望它在一个单独的文件中定义。 但这也没关系。

所以现在,回调事件发生了,我想在View上创建一个带有一些动作的UIButton。 由于我无法从ac函数创建UIButton,我正在调用ViewController类的目标C方法,它创建了UIButton。

希望能够清楚地了解我计划如何使用它。

由于其他人和我自己的说法,您的按钮无法显示:您需要ViewController的现有实例。 您正在创建一个全新的ViewController实例,它永远不会被带到屏幕上或推送等。

您可以使用指向现有实例的全局变量来完成您需要执行的操作。

这是你的.m应该是这样的:

 #import "ViewController.h" static ViewController *viewController = nil; @implementation ViewController - (id)init { if ((self = [super init])) { viewController = self; } return self; } - (void)dealloc { viewController = nil; } -(void) callIncomingCreateButton { 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]; } - (IBAction)DemoCall:(id)sender { callIncoming(1, "a"); } @end int callIncoming(int a, char* b) { [viewController callIncomingCreateButton]; return a; } 

您需要访问正确的ViewController* /实例,而不是任何旧的。 如果你的C函数签名不允许你通过void*或类似的方法传递一些任意数据,那么你需要使用一个类方法和一个静态变量来保存临时指针,如下所示。

在Objective C文件中:

 static ViewController* cLibReceiver = NULL; +(void) callIncomingClassOuter { [cLibReceiver callIncomingClass]; } -(void) beforeTriggerCLibrary { cLibReceiver = self; } 

并在你的(不同的)Objective C文件中使用abc()

 int abc(int a, char* b) { [ViewController callIncomingClassOuter]; } 

在触发C库的位置,您需要这样做:

 [theViewController beforeTriggerCLibrary]; // could be self, depending on context c_library_call(); // optionally set cLibReciever back to NULL. 

注意:我可能在方法标题等方面有一些错误的语法,我对目标C调用约定并不完全熟悉。 类方法绝对是+

注意2:您可能不允许像这样扩展系统类 – 您可能需要定义自己的子类。 再一次,对Objective C不够熟悉。

假设您在Objective-C源文件中,从C函数调用Objective-C函数与从任何其他Objective-C函数调用Objective-C函数完全相同。 在任何一种情况下,如果你有一个指向你想要调用函数的对象的指针ptr ,你就写

 [ptr callIncomingClass]; 

所以当然在任何一种情况下你都需要以某种方式指向你想要调用函数的对象。 如果您使用的是Objective-C函数(例如实例方法),那么这些指针的通常“源”是(a)当您在与当前运行的methid相同的对象上调用方法时隐式的“self”指针( b)调用当前运行的方法的对象的一些实例变量,(c)当前运行的函数或方法的参数,(d)全局变量或某些其他函数调用的结果。 在普通C中你可以使用(c)和(d),但不能使用(a)和(b)因为你没有self