Search code examples
iosobjective-ccin-app-purchasecocos2d-x

Obj C call to Cocos2dx C++ non-static function


I'm writing code for in app purchase in iOS on my cocos2dx game. I want to call my C++ function from Obj C. I can call C++ static function by using *.mm implementation file Obj-C++. But I want to update user interface while the purchasing progress. I've tried to create a singleton class, but the Obj-C still not recognize the function from the singleton object.

C++ : SceneAcc.cpp

void SceneAcc::stateChecker()
{
    if(BridgeObjCpp::sharedBridge()->isPurchasing == false)
   {
       this->unschedule(schedule_selector(SceneAcc::stateChecker));
       removeBuyCash();
   }
}

// There is an update scheduler to check if the purchase phase done

C++ : BridgeObjCpp.mm

BridgeObjCpp* BridgeObjCpp::sharedBridge(){
    if (! s_bridge) {
        s_bridge = new BridgeObjCpp();
    }
    return s_bridge;
}

// Init singleton object
// And bool isPurchasing property in the header

IAPManager.m

- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    NSLog(@"Complete Transaction...");

    // I want something like this
    BridgeObjCpp::sharedBridge()->isPurchase = true;

    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
    [[SKPaymentQueue defaultQueue]finishTransaction:transaction];

}

Solution

  • You need to modify either BridgeObjCpp.mm or IAPManager.m.

    • Add static methods in BridgeObjCpp.mm to handle static objects and in effective BridgeObjCpp.mm will act as wrapper to communicate C++ methods.

    BridgeObjCpp.h

    @interface BridgeObjCpp : NSObject
    
    +(void)setPurchasing:(BOOL)purchasing:
    
    @end
    

    BridgeObjCpp.mm

    @implementation BridgeObjCpp
    
    +(void)setPurchasing:(BOOL)purchasing {
      BridgeObjCpp::sharedBridge()->isPurchase = purchasing ;
    }
    
    @end
    

    IAPManager.m

    [BridgeObjCpp setPurchasing:YES];
    

    OR

    • Rename IAPManager.m to IAPManager.mm to use C++ conventions.

    Note: In .mm files compiler expect a mixture of objective C and C++ codes. In .m files it expect only objective C code. So please do the coding respectively.