将结构中的结构传递给GSourceFunc的最佳方法

时间:2012-06-07 19:05:56

标签: c gtk gobject clutter

哪种方式最好将S转换为GSourceFunc?或者都不是?

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); 
    //...
    }

或者像这样,

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); 
    //...
    }

我尝试了其他方法,但未能使它们发挥作用。 clutter_add_timeout需要将指针作为参数。

1 个答案:

答案 0 :(得分:1)

如果您通过指针将参数传递给clutter_threads_add_timeout_Full,那么您可以只传递St MainStruct成员的地址,从而减少动态分配的需要(对于内部结构)。

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);

编辑:更新代码以动态分配MainStruct结构,以避免ptomato指出的可能的段错误