Search code examples
c++cocos2d-x

Casting types from void*


From what I understand, this should work:

const char* x = "x";
std::cout << x << std::endl;

Passing x into this function:

void myClass::passAsVoid(void* v) {
    std::cout << (const char*)v << std::endl;
}

The first example prints "x";

The second example prints "\350\224A";

I want to learn what's going on, and the correct approach to do this!

The actual code:

float delay = 1;
std::string txt = "random filler text that is not lorum ipsum";
for (int i = 0; i < txt.length(); ++i) {
    const char* x = "x";
    std::cout << x << "code1" << std::endl;
    CCSequence* seq = CCSequence::create(CCDelayTime::create(i*delay),
                                         CCCallFuncND::create( this, callfuncND_selector(OverWorldView::setString), (void*)x ),
                                         NULL);
    this->runAction(seq);
}

Callback function:

void OverWorldView::setString(void* x) {
    std::cout << (const char*)x << "code2" << std::endl;
    label1->setString( (const char*)x );
}

I'm using cocos2dx 2.1.4


Solution

  • It looks like you are not using the API correctly.

    The documentation says you need to use a SEL_CallFuncND type callback, which receives two arguments, not one.

    For everyone's convenience, callfuncND_selector is a macro that hides a static_cast, or probably even a C-style cast (could not find other API versions online) which lets you use just about anything as a callback without getting any compilation errors. Pure joy.