문제

My background experience is C/C++/C#.

I am using a C++ library in an xcode project (to be specific the library is PJSIP). To use the library i have to wire couple of callbacks to my code like this:

SipTest.m

#include < pjsua-lib/pjsua.h >

static void on_reg_state(pjsua_acc_id acc_id)
{
    // Do work
} 

static void Init()
{
   // pjsua_config and psjua_config_default are  defined in the header file from pjsip
    pjsua_config cfg;            
    psjua_config_default(&cfg);  

    cfg.cb.on_regstate = &on_reg_state;
 }

I want to switch this C++ sytnax to Objective C

so I did:

 +(void) on_reg_state:(pjsua_acc_id) acc_id
 {
    // Do work
 } 

 +(void) Init
 {
    pjsua_config cfg;            
    psjua_config_default(&cfg);  

    cfg.cb.on_regstate = &on_reg_state; // ***** this is causing compile error
                                        // I tried [CLASS NAME on_reg_state] and i get   runtime error
 }

I tried to search for delegate in Objective C but i could not find an a similar case where the callback is already implemented in C++ and you want to use it with Objective-C syntax.

Thanks

도움이 되었습니까?

해결책

First of all, there's absolutely no need to convert anything at all. It is perfectly fine to call C++ libraries from Objective-C.

Secondly, whats causing the compiler error is that you're trying to stick a method in a place where there should be a function pointer. You can't make a function pointer out of an Objective-C method using the & Operator. Simply keep your on_reg_state() function and use it as you did before, that's how you do callbacks in Apple's C-based frameworks, too (which you'll need as soon as you move beyond what the high-level Objective-C APIs provide).

And thirdly, your + (void)Init method seems a bit strange. I would strongly discourage you to write a method called Init (capitalized). If you intend to write an initializer, it should be - (id)init, i.e. lowercase and returning id. And don't forget to call the designated initializer of its superclass, check its return value, assign it to self, and return it at the end of the init method (see Implementing an Initializer in Apple's documentation if you're not familiar with that). And if your method is not an initializer, use a different name, e.g. - (void)createConfig.

다른 팁

in this case you'd want to use selectors.

+(void) on_reg_state:(pjsua_acc_id) acc_id
 {
    // Do work
 } 

 +(void) Init
 {
    pjsua_config cfg;            
    psjua_config_default(&cfg);  

    cfg.cb.on_regstate_selector = @selector(on_reg_state:);
    cfg.cb.target = self; //Self here is the class object in your 'Init' method, which is poorly named.
    //Use this like [cfg.cb.target performSelector:cfg.cb.on_regstate_selector withObject:...etc]

 }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top