Pure C function calling Objective-C method?

后端 未结 3 1042
囚心锁ツ
囚心锁ツ 2020-12-31 23:27

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) fun

相关标签:
3条回答
  • 2021-01-01 00:05

    After much experimenting, I found that the most elegant way of solving my problem was to turn my core C library into an NSObject using the .m suffix. The method of calling back and forth resolved instantly. This change DOES alter my original library, but by so little, it's manageable. So to review:

    My original C file was renamed to use the .m suffix. Then I added

    @interface myCLibrary : NSObject
    
    @end
    

    to my .h file, and added to my formerly .c file, now renamed .m.

    @implementation myCLibrary
    
    @end
    

    Just remember that C functions aren't to be pasted between these interface / implementation declarations, below them. Only Objective-C is to go inside these statements. Once I did that, calling the C functions, and calling BACK to other C functions worked great.

    Thanks for all the help regardless.

    0 讨论(0)
  • 2021-01-01 00:15

    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.

    0 讨论(0)
  • 2021-01-01 00:25

    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{
       ...
    }
    
    0 讨论(0)
提交回复
热议问题