views:

81

answers:

3

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 objective-C function is being invoked. How cal I call an objective-C function from within a c function?

Thanks

+1  A: 

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.

Jared P
Thanks. Turns out that the issue was happening due to some memory corruption in the usage of a thirdparty library.
Gary
A: 

[[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

Objective Interested Person
Are you sure you understood my question? :) I wasn't asking about the singleton pattern implementation but about how to call objective-C function from C function.
Gary
A: 
Objective Interested Person