I want to pass a std::list
to my callback function. I understand that I have to work with void*
in my callback function, but how exactly do I insert objects to my list while working with void*
?
//function will insert to a list of albums (data) a new album
int callbackAlbums(void* data, int argc, char** argv, char** azColName)
{
Album album;
for(int i = 0; i < argc; i )
{
if (std::string(azColName[i])) == "NAME")
{
album.setName(std::string(argv[i]));
}
else if (std::string(azColName[i])) == "CREATION_DATE")
{
album.setCreationDate(std::string(argv[i]));
}
else if (std::string(azColName[i])) == "USER_ID")
{
album.setOwner(atoi(argv[i]));
}
}
data.push_back(album);
return 0;
}
//function will return a list of all albums.
const std::list<album> DatabaseAccess::getAlbums()
{
const char* sqlStatement = "SELECT * FROM ALBUMS;";
std::list<Album> albums;
char* errMessage = "";
int res = sqlite3_exec(this->_db, sqlStatement, callbackAlbums, (void*)&albums, &errMessage);
}
I tried changing the void*
in my callback function to std::list<Album>
and expected sqlite3_exec()
to work with that callback function.
CodePudding user response:
You already know how to cast a list*
to a void*
(which BTW, that explicit cast is redundant). Simply do the opposite cast inside the callback, eg:
int callbackAlbums(void* data, int argc, char** argv, char** azColName)
{
Album album;
...
std::list<Album>* albums = (std::list<Album>*)data;
albums->push_back(album);
...
}
And don't forget to actually return
your std::list
from getAlbums()
:
const std::list<album> DatabaseAccess::getAlbums()
{
std::list<Album> albums;
...
int res = sqlite3_exec(..., callbackAlbums, &albums, ...);
...
return albums;
}