1

I was using dlsym() to load a function symbol

void (*func)(int);
func = (func*)dlsym(phandle, "function");

This was resulting in compilation error. However, when I did typedef to function

 typedef void (*func)(int);
 func function = null;
 function = (func*)dlsym(phandle, "function");

This compiled fine, but I fail to understand, why it was failing in first case? Could anyone please tell the reason? I read that C++ standard doesnt allow direct casting from void* to function pointer? Why is this and how did typedef solved this problem?

4

2 回答 2

5

It fails in the first case because func is a variable, not a type, and cannot be used in a cast.

Note the * is misplaced:

typedef void (*func)(int);
           /* ^ must be here. */
于 2013-03-21T10:40:17.467 回答
3

Casting between void * and function pointers is prohibited because it's hard to implement on some platforms.

There are computers (see Harvard architecture) where code and data reside in physically different memories. So, just because you have a pointer to some data, that doesn't mean it makes sense to magially convert that to a pointer to code.

That's why casting to/from void * and functions is not allowed. Sure, on most modern/typical CPUs (by which I mean machines using a von Neumann architecture, not Harvard), the cast will work.

于 2013-03-21T10:42:54.923 回答