将值传递给g_timeout_add_seconds()不起作用?

时间:2015-04-28 20:17:12

标签: c glib

我正在尝试将值传递给g_timeout_add_seconds()中使用的函数,但它没有按预期工作。当我正常地将值传递给函数时它起作用。我是否错误地使用了g_timeout_add_seconds()?

typedef struct { int x, y; } xy_t;

void fn_init(void)
{
  xy_t  xy;
  int    z;

  xy.x =  12;
  xy.y =  23;
  z    = 123;
  pass_thru_test1(&xy);
  pass_thru_test2(&xy);
  pass_thru_test3(&z);

  z = 234;
  g_timeout_add_seconds(1, pass_thru_test3, &z);
}

gboolean pass_thru_test1(xy_t *data)
{
  xy_t *point = (xy_t *)data;
  printf("Pass Thru Test 1: x:%d, y:%d\n", point->x, point->y);
  return TRUE;
}

gboolean pass_thru_test2(gpointer data)
{
  xy_t *p = (xy_t *)data;
  printf("Pass Thru Test 2: x:%d, y:%d\n", p->x, p->y);
  return TRUE;
}

gboolean pass_thru_test3(gpointer data)
{
  int *point = (int *)data;
  printf("Pass Thru Test 3: %d\n", *p);
  return TRUE;
}

结果是:

Pass Thru Test 1: x:12, y:23
Pass Thru Test 2: x:12, y:23
Pass Thru Test 3: 123
Pass Thru Test 3: 724126128
Pass Thru Test 3: 724126128
Pass Thru Test 3: 724126128

1 个答案:

答案 0 :(得分:0)

问题是您正在发送一个指向本地变量的指针作为数据参数。

void fn_init(void)
{
  xy_t  xy;
  int    z; /* this varible is local */

  xy.x =  12;
  xy.y =  23;
  z    = 123;
  pass_thru_test1(&xy);
  pass_thru_test2(&xy);
  pass_thru_test3(&z);

  z = 234;
  g_timeout_add_seconds(1, pass_thru_test3, &z);
}

变量位于fn_init()的堆栈框架中,当您在pass_through*函数中访问它时,它已被释放,因为fn_init()在调用g_timeout_add_secons()后立即返回。

当你完成它时,不要忘记free(z)

gboolean pass_thru_test3(gpointer data)
{
  int *point;
  point = (int *)data;
  if (point == NULL)
      return FALSE;
  printf("Pass Thru Test 3: %d\n", *point);
  free(data);
  return TRUE;
}

有两种可能的解决方案,具体取决于您的功能,请使用malloc()

void fn_init(void)
{
  xy_t  xy;
  int   *z;

  xy.x =  12;
  xy.y =  23;

  z = malloc(sizeof(*z));
  if (z == NULL)
     return;
  *z = 123;

  pass_thru_test1(&xy);
  pass_thru_test2(&xy);
  pass_thru_test3(z);

  *z = 234;
  g_timeout_add_seconds(1, pass_thru_test3, z);
}

您也可以将z设为静态,但每次调用z时它都会相同fn_init(),并且在函数调用中保留修改。