Search code examples
c++sqlitecallbackstatic-methodsfriend

C++ How To Access Member Variables Through A CallBack Method


I'm using SQLite's sqlite3_exec function with Static CallBack functions to handle some information. I want to print out the resulting information to a file defined in a class that called sqlite3_exec. What I'm talking about looks kinda like this,

class MakingTheCall{

static int CallBack(void *NotUsed, int argc, char **argv, char **azColName)
{
    for(int x = 0; x < argc; x++)
        File << argv[x];
    File<<"\n";
} 

private:
   static ofstream File;
   void call(){
       sqlite3_exec(database, query, callback, 0, &zErrMsg);
   }
};

what I REALLY want is for the static function to use a instance specific FILE. So which ever instance of MakingTheCall makes the call passes it's unique non-static FILE object.

But because CallBack is static and must be (I think) to be a callback it doesn't get access to the this pointer of the class. So my thought is if the function where a friend function then it could get at the this pointer. This is assuming I'm understanding this post correctly.

I feel my line of thinking is flawed. It feels like there might still be ambiguity as to which this the function would be using.

As a Part 2 to this discussion is there an example anywhere of where a static friend method would ever be used? They aren't mutually exclusive modifiers from what I'm reading here on the first comment so when would you use both?

I'm new to SQLite and to CallBacks so chances are I could be missing something here that could make my life easy. Like the void* pointer how do I use that? It feels like the key to what I want to do.

Thanks ahead of time.


Solution

  • Pass the object pointer in the sqlite3_exec() call:

    sqlite3_exec(database, query, callback, (void*) this, &zErrMsg);
    

    And you'll get it back in the callback's NotUsed parameter:

    static int CallBack(void *NotUsed, int argc, char **argv, char **azColName)
    {
        MakingTheCall* obj = (MakingTheCall*) NotUsed;
    
        // whatever....
    }
    

    Strictly speaking, the Callback() function should be an extern "C" free function, not a static member.