1

I have 2 files 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.

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. Please suggest the right way of defining and using the callback functions defined in file1.c from file2.c

Thanks in advance

2
  • Assigning a function pointer to an object pointer like void * is undefined behaviour. Us the correct type for the pointers. Commented Oct 22, 2015 at 19:48
  • Thanks a lot. But I am not sure whats the right way of assigning the function pointer locally to some variable/pointer and later using the same variable/pointer in file2.c code. Commented Oct 22, 2015 at 19:53

1 Answer 1

3

Inside of your struct, this:

void *fn_ptr;

Should be defined as this:

void (*fn_ptr)(void);

And setFuncPointer should be defined as:

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

Then in setFuncPointer, you can do this:

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 ( 1, call_to_routine_1 );
setFuncPointer ( 2, call_to_routine_2 );
Sign up to request clarification or add additional context in comments.

3 Comments

@user2618994 Glad I could help. Feel free to accept this answer if you found it useful.
(void) should be used instead of () in the function declaration and in the function pointer type, to indicate that the function takes no parameters. () means any number of parameters, with silent undefined behaviour if the programmer doesn't match up the parameter count when calling the function.
@M.M Good catch. Updated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.