iOS如何从C函数调用静态的Objective-C方法?

3

我正在使用一个旧的库来响应某些事件调用C函数。

我无法向C函数传递参数。我希望C函数将事件引发到Objective-C代码中。

我找不到清晰的示例,而我看到的示例是通过id将参数传递给C函数。我无法在我的代码中传递参数(库将调用C函数)。

如何从C函数调用Objective-C静态/类方法?

//Objective-C class
@interface ActionNotifier : NSObject

+(void)printMessage;

@end

@implementation ActionNotifier

+(void)printMessage {
    NSLog(@"Received message from C code");
}

@end

//response.c source file:
#import "ActionNotifier.h"
#import <Cocoa/Cocoa.h>

void cFunction()
{
    //How can I get the equivalent of this to be called from here?
    [ActionNotifier printMessage]; //error: Expected expression
}

“C类”是什么?你是指“C ++”类吗?你的示例中基本语法看起来不错(尽管它调用了printSecurityMessage但定义了printMessage)。这是纯粹的Objective-C(文件以“.m”结尾)还是Objective-C ++(“.mm”)?我不确定我完全理解你想做什么以及问题所在,因为你提供的代码表面上看起来很好。 - Dirk
抱歉,我的意思是指一个具有 .c 扩展名的 C 源文件。它没有头文件,里面只有一个函数。 - Alex Stone
1
不确定这是否仍然相关,但是由于您使用“.c”作为文件扩展名...在这种情况下,您正在编译纯C,而不是Objective-C,因此方法调用语法将不受支持。尝试将文件重命名为“.m”扩展名(告诉编译器它是Objective-C)。然后您的原始示例应该可以工作(也许您需要先声明类@class ActionNotifier;或包含头文件)。 - Dirk
1个回答

3
根据这个 StackOverflow 回答,您可以将 Objective-C 对象传递给 C 方法。尽管该答案专门处理传递类的实例并调用实例方法而不是静态方法,但您可以尝试在我的理解中,除非我遗漏了什么显而易见的东西,否则它应该可行。
我知道您已经说过这不是理想的方法,因为您的库将调用 C 函数,但也许有另一种方式来传递这个参数?
像这样使用 id 参数定义 C 方法: void cFunction(id param) 然后调用它(某些东西):
Class thisClass = [self getClass];
cFunction(self);

按照以下方式修改您的代码

//Objective-C class
@interface ActionNotifier : NSObject

+(void)printMessage;

@end

@implementation ActionNotifier

+(void)printMessage {
    NSLog(@"Received message from C code");
}

@end

//C class:
#import "ActionNotifier.h"
#import <Cocoa/Cocoa.h>
void cFunction(id param)
{
    [param printSecurityMessage];
}

如果这不可接受

你可以利用Core Foundation中的NSNotificationCenter,如这篇StackOverflow文章所述。但是,如果你需要[ActionNotifier printMessage]是静态的,你需要在其他地方进行[NSNotificationCenter addObserver]的连接。

//NSNotificationCenter Wire-up

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method), @"MyNotification", nil];
-(id)method{
    [ActionNotifier printMessage];
}

//Objective-C class
@interface ActionNotifier : NSObject

+(void)printMessage;

@end

@implementation ActionNotifier

+(void)printMessage {
    NSLog(@"Received message from C code");
}

@end

//C source: //may need to rename to .mm if you cannot see the core foundation
#include <CoreFoundation/CoreFoundation.h>
void cFunction()
{
    CFNotificationCenterRef center = CFNotificationCenterGetLocalCenter();
    CFNotificationCenterPostNotification(center, CFSTR("MyNotification"), NULL, NULL, TRUE);
}

1
谢谢,通知中心的使用看起来很有前途! - Alex Stone

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接