Pure C function calling Objective-C method?

Viewed 6315

Okay, I've read half a dozen threads on this subject, but none of the solutions appear to address exact needs.

Question:

How does a Pure C (.c) function call a method inside a Pure Objective-C (.m) class?

Every example / answer is using C inside an Objective-C (.m) method. I have a Pure C library that I have to create a simulator for, so I need to keep my Kernel in pure C and call out to my higher level emulation methods in Objective-C.

Any attempt I make to create a reference and call a method fails. Square bracket notation fails as well. Creating a global var in Obj-C and trying to use that in Pure-C doesn't work, as if the namespace is segregated.

Anyone done this?

Here's a diagram of the flow:

Obj-C UIButton CLICKED->Calls Obj-C method->Calls C function->Call Obj-C method

3 Answers

Objective C can compile c method without any modification. To call c method from objective-c class you have to whatever you do in c, just include the header file then call method directly. Suppose you have a C header named test.h and in that you have a method sum(int i, int j); then first include test.h and then call test(1, 2);

If you want to call C++ method, use Objective-C++ (.mm extension) in the same manner as explained above.

I hope i understand you correctly!

You can do this via callback-function.

In you C file use this:

Define the callback-type

eventcallback g_callback;

Implement callback-class (executed by objective-c code)

void comm_set_callback(eventcallback callback){
   g_callback = callback;
}

in objective-c:

Set the callback (i.e.: in viewDidLoad())

comm_set_callback(&testfkt);

C-Method called from extern C-function

void testfkt(){
 [refToSelf testmethod];
}

Objective-C Method called from C-Method testfkt

-(void)testmethod{
   ...
}
Related