gpt4 book ai didi

c++ - 在 C++ 中使用 SQLite : object function as a callback

转载 作者:太空狗 更新时间:2023-10-29 23:04:53 28 4
gpt4 key购买 nike

所以,我正在做一个副项目来保持我的 c++ 技能新鲜(我已经有很多年没有用 c++ 工作了)。我正在做一些我将使用 SQLite 的事情。我有一个 SQLite 代码的包装器。我注意到的一件事是 SQLite 在其 sqlite3_exec(...) 函数中使用了 c 风格的回调函数。

我希望回调函数是一个对象方法,因为我希望它能够修改对象变量,但不确定如何准确地做到这一点。我在 stackoverflow 上检查了其他类似的问题,但没有任何帮助。

这是我声明包装器类的方式:

class DBAdapter
{
private:
sqlite3* db;
int getUserRecords(std::string);
std::vector<USER_RECORD> records;

int callbackSel(void*, int , char**, char**);

public:
DBAdapter();
~DBAdapter();

int open(std::string);
void close();

int insertRecord();
int deleteRecord();
int getNumUserRecords();
};

下面是我尝试使用 getNumUserRecords 中的回调 (callbackSel) 的方式:

int DBAdapter::getUserRecords(std::string name)
{
std::string sql = "SELECT" + name + " from USERS";
char* ErrMsg;
char* data;

int retval = sqlite3_exec(db,sql.c_str(),this->callbackSel,data,&ErrMsg);
return retval;
}

我得到的错误信息是:

 error: ‘int (* DBAdapter::callbackSel)(void*, int, char**, char**)’ is not a static member of ‘class DBAdapter’

我的问题是,如果我将其设为静态函数,我将无法访问我的 vector 记录,对吗?有什么办法解决这个问题吗?

最佳答案

Is there any way around this?

我不知道 API 具体来说,但通常 c 风格的回调支持从 void* 指针传递用户数据(我猜你提到的那个签名的第一个参数)。通常做的是:

  1. 声明一个静态类函数指定为回调函数指针
  2. 实现该函数以将传递的用户数据指针转换为指向您的类实例的指针并调用成员函数
  3. 在提供所需实现的类中定义一个成员函数
  4. 当您要使用 C API 注册静态成员函数指针时,将指针传递给您的处理类实例

我希望这指出了正确的方向。

关于c++ - 在 C++ 中使用 SQLite : object function as a callback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21243997/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com