简体   繁体   中英

sqlite3 change in the func callback the parameter void* notUsed to int* C++

I need to return a integer from callback, but I not succeeded. I tried - but nothing. I will be very glad if you will help me.

Here is my code:

using namespace std;
int main()
{
    sqlite3* db;
    char* zErrMsg;
    sqlite3_open("try.db", &db);

    //do something...

    string query = "select * from myTable";
    int *ptr;
    sqlite3_exec(db, query.c_str(), callback, ptr, &zErrMsg);

    cout << ptr << endl;

    system ("pause");
    return 0;
}



int callback(void* notUsed, int argc, char** argv, char** azCol)
{
    /*
    chane void* notUsed to int*
    ???how???
    */

    return 0;
}

You have to pass an address of valid memory (eg on stack) or allocate it (heap) to the callback function, if you allocate you have to free it also.

The forth argument of the sqlite3_exec() function will be the first argument of the callback() function wich is of type void* . So if you pass the address of an int you have to interpret the void* as an int* .

I changed it so the memory ( int someNumber ) is in the callers function (main) and pass the address of it. In the callback function you need to cast the void* to the pointer type you expect, here int* and assign a value.

It should be:

...
int main()
{
    ...
    int someNumber;
    sqlite3_exec(db, query.c_str(), callback, &someNumber, &zErrMsg);

    cout << someNumber << endl;
    ...
}

int callback(void* someNumberArg, int argc, char** argv, char** azCol)
{
    int* someNumber = reinterpret_cast<int*> (someNumberArg);
    *someNumber = 42;
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM