mardi 2 juin 2015

how to get result which is returned with C callback in C++

I am rather new to handle C callbacks in C++. I made a sqlite wrapper c++ class, which just calls sqlite3_exec().

static int callback(void *NotUsed, int argc, char **argv, char **azColName){
  SqliteAccessor* sqlite = static_cast<SqliteAccessor*> NotUsed; 
  if(argc > 0) { 
    m_table_exists = true; 
  }
  return 0;
}

class SqliteAccessor{    
public:
bool has_table(const string dbName, const string tblName)
{
  bool hasTable = false;
  string sql;
  sql = "SELECT " + quote_string(tblName) + "FROM " + quote_string(dbName)
           + "WHERE type = 'table' AND name = " + quote_string(tblName) + ";";
  char *zErrMsg = 0;
  int rc = sqlite3_exec(m_db, sql.c_str(), callback, (void*) this, &zErrMsg);
  if( rc != SQLITE_OK ){
    printf("SQL error: %s", zErrMsg);
    sqlite3_free(zErrMsg);
  }
  return hasTable;
}
};

int caller(){
   SqliteAccessor sqlite;
   // to check if table exist
   if (sqlite->has_table()){
      // will above work or 
      // I should do with an extra call to query the changed state?        
   }
}

Now, I am quite confused how the caller can get the result from sqlite wrapper. I think, the caller cannot have the result by simply calling has_table(), because the result is returned from callback. So shall the caller get the result by making another call, e.g. call sqlite->get_result_has_table()?

Then this implies for every callback, I need to make a state in class SqliteAccessor, which will be very cumbersome. How to design the class to make it nice to use by caller?

Aucun commentaire:

Enregistrer un commentaire