当前位置: 动力学知识库 > 问答 > 编程问答 >

Need advice about function pointers in C

问题描述:

I have two functions with following signatures:

int f1(void* data);

and

int f2(const void* data);

Then I do this:

int (*f) (void*) = f2;

E.g. I need one pointer type to refer to both functions. However, I get a warning because of removing that const modifier. Is there any way around that? (I can't change f1 and f2 signatures)

Let me explain why I need this. The thing is I was writing wrappers for read() and write() system calls and I noticed that both of them were identical except for call to read() or write(). So I decided to make one wrapper function and pass the needed function using a pointer. So it's all just to get rid of copy-paste. And now I'm not sure if it was a good idea at all.

网友答案:

Is an union working ?

union generic_void
{
    void       *data;
    void const *const_data;
} generic_void_t;

int (*f) (generic_void_t) = f1;
int (*f) (generic_void_t) = f2;
网友答案:

f1 anf f2 have different signatures and creating a pointer capable of taking either value is prone to undefined behavior.

I need one pointer type to refer to both functions. ... Is there any way around that?

Do not include a signature in the function pointers arguments.

int f1(void* data);
int f2(const void* data);

int fooy(void) {
  int (*fp1)() = f1;
  int (*fp2)() = f2;
  void* data1;
  const void* data2;
  return (*fp1)(data1) + (*fp2)(data2);
}

This defeats type checking in (*fp1)(data1) + (*fp2)(data2) as code could call (*fp1)(data2) or (*fp2)(1,2,3). Code is on the precipice.

分享给朋友:
您可能感兴趣的文章:
随机阅读: