转换sqlite回调的函数类型
我正在使用sqlite编写程序。我有类 dataSend_task
,该类定期从BD中选择数据并将其发送到服务器。
I'm writing program using sqlite. I've got class dataSend_task
, that periodicaly select data from BD and send it to server.
在 dataSend_task
我有方法 callback
,我想将它作为参数发送给 sqlite3_exec
。
In dataSend_task
i've got method callback
, that I want to sent as argument to sqlite3_exec
.
我遇到了错误:
error: cannot convert ‘std::function<int(void*, int, char**, char**)>’ to ‘int (*)(void*, int, char**, char**)’ for argument ‘3’ to ‘int sqlite3_exec(sqlite3*, const char*, int (*)(void*, int, char**, char**), void*, char**)’
if (sqlite3_exec(this->db, this->SQL_SELECT_READINGS_QUERY, callback, 0, &err)) {
源代码部分:
int dataSend_task::callback(void *NotUsed, int argc, char **argv, char **columnName){...}
void dataSend_task::sendData()
{
using namespace std::placeholders;
std::function<int(void *, int, char **, char **)> callback =
std::bind(&dataSend_task::callback, this, _1, _2, _3, _4);
if (sqlite3_exec(this->db, this->SQL_SELECT_READINGS_QUERY,
callback, 0, &err))
{ ... }
}
据我了解,问题在于转换回调
键入 sqlite_exec
接受的值。但我不知道如何解决。
As I understand problem is in converting callback
to type that sqlite_exec
accepts. But I don't know how to fix it.
您不能将 std :: function
转换为函数指针。但是,您仍然可以使用lambda完成所需的操作。多亏了一些法宝,可以将没有捕获的lambda转换为函数指针(正是您所需要的)。另请注意, sqlite3_exec()
为第一个参数接受 void *
-因此您可以在no-中使用它捕获lambda以实际调用您的成员函数:
You cannot convert a std::function
to a function pointer. However, you can still accomplish what you want with a lambda. Thanks to some sorcery, a lambda with no capture can be converted to a function pointer (exactly what you need). Notice also that sqlite3_exec()
accepts a void*
for the 1st argument - so you can use that in your no-capture lambda to actually call your member function:
if (sqlite3_exec(this->db, this->SQL_SELECT_READINGS_QUERY,
+[](void* instance, int x, char** y, char** z) {
return static_cast<dataSend_task*>(instance)->callback(x, y, z);
},
this,
&err))
{
/* whatever */
}