I am try to implement an cocoa application For USB Detection. Wh开发者_如何学Goenever user connects the USB it automatically detected, this entire part is one C program (Normal C) is orking Fine.
My need is if the system detects a particular USB device, I want to call another application (i.e. another cocoa application) using system function. I open that application, but my problem is if the user removes that USB device (this is also detected in C program), I want to close the second application automatically.
Or, if I add a cocoa user interface/objective-c class in the first application, is it possible to call that class from inside the C program?
One class you could use for this is NSDistributedNotificationCenter
. Your C program would need to post notifications and your other program(s) would subscribe to them. The scenario would go like this:
- Second App: on launch register to receive "USB Device Removed" messages
- C Program: dectect removed USB device
- C Program: post notification "USB Device Removed"
- Second App: receives notification "USB Device Removed"
- Second App: quits itself
Of course your C program would now become an objective-c program. There is also C alternative, which is CFNotificationCenterGetDistributedCenter
.
If the object already exists and you can pass a pointer to it, you can use the Objective-C runtime function objc_msgSend
. For example:
#include <objc/runtime.h>
#include <objc/message.h>
void sendDoneToApp(id app)
{
/* [app done]; */
/* get selector for "done" */
SEL doneSel = sel_registerName("done");
/* cast objc_msgSend to the type we need */
void (*sendNoArgsNoRet)(id obj, SEL selector) = (void (*)(id, SEL))objc_msgSend;
/* send the message */
sendNoArgsNoRet(app, doneSel);
}
Yes it is possible. You could for example look at how libdispatch/Grand Central Dispatch manages this.
The basic idea is to pass C function-pointers + void-pointers to your C library. And then in the passed function you can call Obj-C functions. Example:
struct test_s {
NSString *my_string;
};
void my_function(void *data) {
struct test_s *context = data;
NSLog(@"%@", [@"Hello " stringByAppendingString:context->my_string];
}
void main(void) {
struct test_s context = { @"World!" };
/* dispatch_sync_f is a C function unaware of Obj-C */
dispatch_sync_f(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
&context,
my_function);
}
精彩评论