我正在使用旧版库,该库可以响应某些事件来调用C函数。
i无法将参数传递到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
}
根据此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];
}
如果这是不可接受的
根据此stackoverflow帖子,您可以在核心基础中利用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);
}