I'm trying to pass in a std::vector<std::string>
to a void*
for use in a callback function which requires a void*
to be passed to it. The callback is a sqlite_exec
callback. However, I am getting a segfault when casting vec
to a void*
. So how can I pass in a std::vector<std::string>
into such a callback?
static int cb_vector(void* vec, int argc, char**argv, char**colNm){
std::vector<std::string>* myvec = (std::vector<std::string>*)vec;
for(int i = 0; i < argc; i++){
myvec->push_back(argv[i]);
}
return 0;
}
std::vector<std::string> myfunc(){
std::vector<std::string> vec;
int rc = sqlite3_exec(_db, SQL, cb_vector, (void*)&vec, NULL);
return vec;
}
I have already looked the following resources, but they did not answer my quesion.
First of all void *
specially designed to accept pointer to any data, so your explicit cast to it is not necessary. Second - you better use C++ cast in C++ code:
std::vector<std::string>* myvec = static_cast<std::vector<std::string>*>( vec );
At least it is easier to catch problems later when you use keyword for your cast.
According to sqlite3_exec documentation:
The 3rd argument to the sqlite3_exec() callback is an array of pointers to strings obtained as if from sqlite3_column_text(), one for each column. If an element of a result row is NULL then the corresponding string pointer for the sqlite3_exec() callback is a NULL pointer.
Most probably you get nullptr
and try to push it into vector
. Put additional check there:
myvec->push_back(argv[i] ? argv[i] : std::string() );
or deal with it accordingly
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.