简体   繁体   English

sqlite3在func回调中更改参数void * notnott to int * C ++

[英]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* . sqlite3_exec()函数的第四个参数将是callback()函数的第一个参数,其类型为void* So if you pass the address of an int you have to interpret the void* as an int* . 因此,如果传递int的地址,则必须将void*解释为int*

I changed it so the memory ( int someNumber ) is in the callers function (main) and pass the address of it. 我对其进行了更改,以便内存( int someNumber )位于调用方函数(main)中,并传递其地址。 In the callback function you need to cast the void* to the pointer type you expect, here int* and assign a value. 在回调函数中,您需要将void*为所需的指针类型,此处为int*并分配一个值。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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