根据
这个 StackOverflow 回答,您可以将 Objective-C 对象传递给 C 方法。尽管该答案专门处理传递类的实例并调用实例方法而不是静态方法,但您可以尝试在我的理解中,除非我遗漏了什么显而易见的东西,否则它应该可行。
我知道您已经说过这不是理想的方法,因为您的库将调用 C 函数,但也许有另一种方式来传递这个参数?
像这样使用 id 参数定义 C 方法:
void cFunction(id param)
然后调用它(某些东西):
Class thisClass = [self getClass];
cFunction(self);
按照以下方式修改您的代码
@interface ActionNotifier : NSObject
+(void)printMessage;
@end
@implementation ActionNotifier
+(void)printMessage {
NSLog(@"Received message from C code");
}
@end
#import "ActionNotifier.h"
#import <Cocoa/Cocoa.h>
void cFunction(id param)
{
[param printSecurityMessage];
}
如果这不可接受
你可以利用Core Foundation中的NSNotificationCenter
,如这篇StackOverflow文章所述。但是,如果你需要[ActionNotifier printMessage]
是静态的,你需要在其他地方进行[NSNotificationCenter addObserver]
的连接。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method), @"MyNotification", nil];
-(id)method{
[ActionNotifier printMessage];
}
@interface ActionNotifier : NSObject
+(void)printMessage;
@end
@implementation ActionNotifier
+(void)printMessage {
NSLog(@"Received message from C code");
}
@end
#include <CoreFoundation/CoreFoundation.h>
void cFunction()
{
CFNotificationCenterRef center = CFNotificationCenterGetLocalCenter();
CFNotificationCenterPostNotification(center, CFSTR("MyNotification"), NULL, NULL, TRUE);
}
printSecurityMessage
但定义了printMessage
)。这是纯粹的Objective-C(文件以“.m”结尾)还是Objective-C ++(“.mm”)?我不确定我完全理解你想做什么以及问题所在,因为你提供的代码表面上看起来很好。 - Dirk@class ActionNotifier;
或包含头文件)。 - Dirk