简体   繁体   English

将函数指针分配给变量

[英]Assign a Function Pointer to a variable

I have 2 files file1.c file2.c. 我有2个文件file1.c file2.c。 I need to store the Function Pointers passed from file1.c to file2.c in a struct array of size 2. 我需要在大小为2的结构数组中存储从file1.c传递到file2.c的函数指针。

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 */
}

Also, I am unsure of declaring the void pointer inside the struct. 另外,我不确定在结构中声明void指针。 Please suggest the right way of defining and using the callback functions defined in file1.c from file2.c 请建议正确的方法来定义和使用file2.c中file1.c中定义的回调函数

Thanks in advance 提前致谢

Inside of your struct, this: 在你的结构内部,这个:

void *fn_ptr;

Should be defined as this: 应该定义为:

void (*fn_ptr)(void);

And setFuncPointer should be defined as: 并且setFuncPointer应该定义为:

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

Then in setFuncPointer , you can do this: 然后在setFuncPointer ,您可以这样做:

func[0].fn_ptr = cal_fun;

Later on, you can call the function like this: 稍后,您可以像这样调用函数:

func[0].fn_ptr();

Also, it's sufficient to call setFuncPointer like this: 此外,调用setFuncPointer就足够了:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM