Search code examples
cgtkgobjectclutter

Best way to pass a struct within a struct to a GSourceFunc


Which way is best to get S to a GSourceFunc? Or neither?

typedef struct{
//...
}S;

struct MS{
//..
S *St;
};

static gboolean AL_Calback(gpointer data){
    S *St = (S*)user_data;
    St->Something = SomethingElse;
    return TRUE;
} 

int main (int argc, char *argv[]){

    //...
    MS *MainStruct = gnew0(MS, 1);
    Mainstruct->St = gnew0(S, 1);
    clutter_threads_add_timeout_full(G_PRIORITY_HIGH, 100, AL_Callback, MainStruct->St, NULL); 
    //...
    }

or like this,

typedef struct{
//...
}S;

struct MS{
//..
S St;
};

static gboolean AL_Calback(gpointer data){
    MS *MV = (MS*)user_data;
    MV->S.something = SomethingElse;    
    return TRUE;
} 

int main (int argc, char *argv[]){

    //...
    MS *MainStruct = gnew0(MS, 1);
    clutter_threads_add_timeout_full(G_PRIORITY_HIGH, 100, AL_Callback, MainStruct, NULL); 
    //...
    }

I've tried other ways, but have not been able to make them work. clutter_add_timeout needs to take a pointer as an argument.


Solution

  • If you are passing the parameter to clutter_threads_add_timeout_Full via pointer, then you could just pass the address of the St member of MainStruct thus reducing the need for dynamic allocation (for the inner structure).

    struct MainStruct{
      //..
      S St; // note: no pointer
    };
    
    // in main
    MainStruct* ms = gnew0(MS, 1);
    clutter_threads_add_timeout_Full(G_PRIORITY_HIGH, 100, AL_Callback, &(ms->St),
        NULL);
    

    Edit: updated code to dynamically allocate MainStruct structure to avoid possible segfault as pointed out by ptomato