Reputation: 13
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;
}
Upvotes: 0
Views: 669
Reputation: 5631
You have to pass an address of valid memory (e.g. 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;
}
Upvotes: 2