2017-09-02 49 views
0

我需要訪問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

將類的'this'指針通過_1st參數傳遞給回調參數_參見:https://sqlite.org/c3ref/exec.html –

+0

'bin = new char [lenght]; bin = argv [3];'爲什麼你只分配內存來泄漏它在下一行? – 2017-09-02 15:31:51

+0

更改爲sqlite3_exec(db,tQuery.c_str(),this-> callback,(void *)data,&errmsg);我有這個錯誤:/root/Dokumenty/musicdb/funcs.h|94|error:無效使用非靜態成員函數int fromdb :: callback(void *,int,char **,char **)'| – BigAdam

回答

1

你越來越未定義的引用,因爲你正在嘗試使用非靜態成員從靜態函數。

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

你仍然可以使用一個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)