xeroblast
xeroblast

Reputation: 21

c++ calling a class function/data from a non-member

i am currently making a simple sqlite3 wrapper base on this tutorial ( http://www.tutorialspoint.com/sqlite/sqlite_c_cpp.htm )

my problem is about the callback function in querying.

static int callback(void *data, int argc, char **argv, char **azColName){
  int i;
  fprintf(stderr, "%s: ", (const char*)data);
  for(i=0; i<argc; i++){
    printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
  }
  printf("\n");
  return 0;
}

callback function is not a member function of a class

class Wrapper() {
  public:
    Wrapper();
    ~Wrapper();
  private:
    vector<map<string, string> > result;
};
static int callback(){
  result.insert( ...data... );
}

how will i do go around with this. help is very much appreciated. thanks...

Upvotes: 2

Views: 247

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254561

Use the data argument to pass a pointer to a class object.

static int callback(void *data, int argc, char **argv, char **azColName){
  Wrapper * wrapper = static_cast<Wrapper*>(data);
  wrapper->result.insert( ...data... );
}

passing a suitable pointer to the sqlite function that uses the callback

Wrapper my_wrapper;
rc = sqlite3_exec(db, sql, callback, &my_wrapper, &err_msg);

Note that the callback will have to be a friend or static member to access result directly, as the example does. It can be a non-member if it only uses the public interface.

Upvotes: 2

Related Questions