如何访问成员变量sqlite回调

时间:2017-09-02 15:09:23

标签: c++ oop sqlite

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

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'

1 个答案:

答案 0 :(得分:1)

您正在获取未定义的引用,因为您正在尝试使用静态函数中的非静态成员。

  

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

您仍然可以使用static功能,但您需要将成员传递为@Richard Critten points out in the comments,或者您可以使用friend功能。

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

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)