如何访问成员变量sqlite回调 [英] How to access member variables sqlite callback

查看:93
本文介绍了如何访问成员变量sqlite回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从sqlite回调函数访问类中的变量.它不能是静态的,因为我需要从其他函数访问此变量.这是我当前的代码.

I need access variables in class from sqlite callback function. It cannot be static because i need acces this variables from other functions. This is my current code.

class fromdb {
private:
   string paramdb;
   char* errmsg;
   string param;
   string title;
   string creator;
   char* bin;
public:
     static int callback(void *data, int argc, char **argv, char **azColName){
        int lenght;
        lenght = sizeof(*argv[3]);
        title = *argv[1];
        creator = *argv[2];
        bin = new char[lenght];
        bin = argv[3];
        return 0;
}
void getdata() {
string tQuery = "SELECT * FROM test WHERE " + paramdb + "=\"" + param + "\" )";
  sqlite3_exec(db, tQuery.c_str(), fromdb::callback, (void*)data, &errmsg);
}
};

日志

undefined reference to `fromdb::title[abi:cxx11]'
undefined reference to `fromdb::creator[abi:cxx11]'
undefined reference to `fromdb::bin'

推荐答案

由于尝试使用静态函数中的非静态成员,因此您获得了未定义的引用.

You're getting undefined references because you are attempting to use non-static members from a static function.

它不能是静态的,因为我需要从其他函数访问此变量

It cannot be static because I need access this variables from other functions

您仍然可以使用static函数,但是您需要以

You can still use a static function, but you need to pass a member in, as @Richard Critten points out in the comments, or you can use a friend function.

在这里,我已经使用类似的static函数创建了一个更简单的代码版本,以进行演示,但是传入了成员变量:

Here I've created a more simple version of your code to demonstrate, using a static function like you have, but passing in the member variable:

class artwork
{
private:
    std::string title;
    std::string creator;
public:
    static int populateFromDB(void* object, int, char** data, char**)
    {
        if (artwork* const art= static_cast<artwork*>(object))
        {
            art->title = data[1];
            art->creator = data[2];
        }
        return 0;
    }
};

artwork a;
char* error = nullptr;
if (sqlite3_exec(db, tQuery.c_str(), &artwork::populateFromDB, static_cast<void*>(&a), &error) != SQLITE_OK)
    sqlite_free(error)

或作为friend函数代替:

class artwork
{
    friend int getArtwork(void*, int, char**, char**);
private:
    std::string title;
    std::string creator;
};    
int getArtwork(void* object, int, char** data, char**)
{
    if (artwork* const art = static_cast<artwork*>(object))
    {
        art->title = data[1];
        art->creator = data[2];
    }
    return 0;
}

artwork a;
char* error = nullptr;
if (sqlite3_exec(db, tQuery.c_str(), &getArtwork, static_cast<void*>(&a), &error) != SQLITE_OK)
    sqlite_free(error)

这篇关于如何访问成员变量sqlite回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆