我正在使用旧式库,该库允许我响应某些事件而调用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
}
答案 0 :(得分:3)
根据this StackOverflow answer,您可以将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];
}
如果不能接受
您可以按照This StackOverflow post在Core Foundation中使用NSNotificationCenter
,尽管如果您需要[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);
}