【问题标题】:Assign a Function Pointer to a variable将函数指针分配给变量
【发布时间】:2015-10-22 19:43:21
【问题描述】:

我有 2 个文件 file1.c file2.c。我需要将从 file1.c 传递到 file2.c 的函数指针存储在一个大小为 2 的结构数组中。

file1.c

main ()
{
   setFuncPointer ( 1, &call_to_routine_1 );
   setFuncPointer ( 2, &call_to_routine_2 );

void call_to_routine_1 ()
{
  // Do something
}
void call_to_routine_2()
{
  // Do something
}
}

file2.c

struct store_func
{
  UINT32 Id;
  void *fn_ptr;
} func[2];

void setFuncPointer( UINT32 id, void(*cal_fun)())
{
   func[0].id = id;
   /* How to assign the cal_fun to the local fn_ptr and use that later in the code */
}

另外,我不确定在结构中声明 void 指针。请提出正确的方法来定义和使用 file1.c from file2.c 中定义的回调函数

提前致谢

【问题讨论】:

  • 将函数指针分配给像void * 这样的对象指针是未定义的行为。使用正确的指针类型。
  • 非常感谢。但我不确定将函数指针在本地分配给某个变量/指针并稍后在 file2.c 代码中使用相同的变量/指针的正确方法。

标签: c


【解决方案1】:

在你的结构里面,这个:

void *fn_ptr;

应该这样定义:

void (*fn_ptr)(void);

setFuncPointer应该定义为:

void setFuncPointer( UINT32 id, void(*cal_fun)(void))

然后在setFuncPointer,你可以这样做:

func[0].fn_ptr = cal_fun;

稍后,您可以像这样调用该函数:

func[0].fn_ptr();

另外,像这样调用setFuncPointer 就足够了:

setFuncPointer ( 1, call_to_routine_1 );
setFuncPointer ( 2, call_to_routine_2 );

【讨论】:

  • @user2618994 很高兴我能提供帮助。如果您觉得有用,请随时 accept this answer
  • (void) 应在函数声明和函数指针类型中使用,而不是 (),以表明该函数不带参数。 () 表示任意数量的参数,如果程序员在调用函数时未匹配参数计数,则具有静默未定义行为。
  • @M.M 很好。已更新。
猜你喜欢
  • 1970-01-01
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-24
  • 2013-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多