How to call objective-C function from a C function
I'm trying to call an objective-C function from a C function but the code keeps crashing in objc_msgSend.
My objective-C class is a singleton and I'm using the following code.
void c_function(int arg0, const char *arg1)
{
[[objc_class instance] testFunction:arg0 Arg1:arg1];
}
The gdb shows the crash is happening when ob开发者_JAVA技巧jective-C function is being invoked. How cal I call an objective-C function from within a c function?
Thanks
There's nothing wrong with your code as there are no special rules for calling objc methods from c functions. If there is a crash in objc_msgSend, then refer to http://www.sealiesoftware.com/blog/archive/2008/09/22/objc_explain_So_you_crashed_in_objc_msgSend.html. The same thing would have happened if the objc line was in other objc code -- it's likely you forgot to retain the shared instance of your singleton.
[[objc_class instance] testFunction:arg0 Arg1:arg1];
As you don’t provide further information:
objec_class is an instance, your singleton? And it handles the message instance? …
or
objec_class is really a class, having a class method instance? And this will give you another instance …
In other words, do you really have something like
@interface class2 {
}
-(void) testFunction:(int)count Arg1:(const char *)args;
@end
and
@include "class2.h"
@interface objc_class {
}
-(class2*) instance {
}
-(void) testFunction:(int)count Arg1:(const char *)args;
@end
or
@include "class2.h"
@interface objc_class {
}
+(class2*) instance;
// be aware of the fact, instance (normaly) does not have
// access to any instance variables!
to be included?
Your code doesn’t look like „hey, object(instance) singleton, I tell you to ‘instance’. Then I take your response and give it the message ‘testFunction:Arg1:’ (with some values inserted)”!
(Are you sure you understood objective c?)
Greetings
1:
@interface class2 {
}
-(void) testFunction:(int)count Arg1:(const char *)args;
@end
2:
@include "class2.h"
@interface objc_class {
}
-(class2*) instance;
@end
3:
@include "class2.h"
@interface objc_class {
}
+(class2*) instance; // be aware of the fact, instance (normally) does not
// have access to any instance variables!
精彩评论