簡體   English   中英

將函數指針分配給變量

[英]Assign a Function Pointer to a variable

我有2個文件file1.c file2.c。 我需要在大小為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 */
}

另外,我不確定在結構中聲明void指針。 請建議正確的方法來定義和使用file2.c中file1.c中定義的回調函數

提前致謝

在你的結構內部,這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM