How to pass a int as parameter in CCCallFuncND::actionWithTarget ?

Hi,

I have got the following code:

int intValue = 3;
int *value = (int*) intvalue;
CCLog("*value = %d", *value); //=> I get 3 here => ok
 _coinsLabel->runAction((CCSequence*)CCSequence::actions(
                                                                CCDelayTime::actionWithDuration(.05f),
                                                                CCCallFuncND::actionWithTarget(this, callfuncND_selector(GameLayer::addCoins),(void*) value),
                                                                NULL));

calling the following method:

void GameLayer::addCoins(void* intvalue)
{
    int *value = (int*) intvalue; 

    CCLog("*value = %d", *value); //=> I get 12564789 here... Adress and not the int ? Why ?

  // some code...
}

How can I do to pass my int properly with CCCallFuncND::actionWithTarget to my addCoins method ?

Thanks

Yes, it will be a wrong value, because the pointer ‘value’ points to a temporary variable ‘intValue’, it will be destroyed after the function returns.
So you should allocate the memory on heap rather than on stack. For example, int* value = new int(3);and invoke ‘delete value’ at the end of void GameLayer::addCoins(void* intvalue).

Thanks for your answer James. I changed my code as you propose but still get the same issue… Any other idea ?

Perhaps the code “int *value = (int*) intvalue;” to recover the value in addCoins in wrong ? Or the declaration of the method addCoins “void GameLayer::addCoins(void* intvalue)” ?

Thanks for your help.

Hi, you should declare the function like ‘void addCoins(CCNode* sender, void* data);’

int *value = new int(3);
CCLog("*value = %d", *value); //=> I get 3 here => ok
 _coinsLabel->runAction((CCSequence*)CCSequence::actions(
                                                                CCDelayTime::actionWithDuration(.05f),
                                                                CCCallFuncND::actionWithTarget(this, callfuncND_selector(GameLayer::addCoins),(void*) value),
                                                                NULL));

void GameLayer::addCoins((CCNode* sender, void* data)
{
    int *value = (int*) data; 

    CCLog("*value = %d", *value);

  // some code...
   delete value;
}

James, you are just a genius Thank you so much !

If you are able to explain to me why it is necessary to add the parameter CCNode* sender (which is nit used) to make this working, you will be awarded “double genius” :slight_smile: Just curiosity but I would be interested to know the reason !

Many thanks anyway !

1 Like