开发者

A complicated situation while using dlsym casting

开发者 https://www.devze.com 2022-12-07 20:49 出处:网络
In our code there is a function defined as: a.h extern int (*get_prof_action(void))(void); a.c static int (*ProfAct开发者_Go百科ion)(void) = NULL;

In our code there is a function defined as:

a.h

extern int (*get_prof_action(void))(void);

a.c

static int (*ProfAct开发者_Go百科ion)(void) = NULL;

int (*get_prof_action(void))(void)
{
    return ProfAction;
}

Then later in main.c, I want to gain this function through dlsym(I have to), so I used like this.

...
int (*p_get_prof_action(void))(void);
...

void my_function(){

...
void *handle=dlopen(mylibrary,RTLD_LAZY);
p_get_prof_action = (int (*(void))(void)) dlsym(handle,"get_prof_action");
...

}

And I got compile error:

error: cast specifies function type at line
(int (*(void))(void)) dlsym(handle,"get_prof_action");
=======================================================

Here are my questions:

  1. This is not my code and I never saw such usage to define a function. Could you let me know what is this?

  2. How do I correctly get this p_get_prof_action?

Thanks very much. This really stucks me a lot!!


You've declared p_get_prof_action as a function, not a function pointer. The correct declaration would be:

int (*(*p_get_prof_action)(void))(void);

And the correct cast would be:

p_get_prof_action = (int (*(*)(void))(void)) dlsym(handle,"get_prof_action")

When dealing with function pointers, a typedef can be very helpful. The function in question is returning a function pointer, so let's make one for the return type:

typedef int (*action)(void);

Then declare your function pointer to return that type:

action (*p_get_prof_action)(void);

And assign to it like this:

p_get_prof_action =  (action (*)(void))dlsym(handle,"get_prof_action");
0

精彩评论

暂无评论...
验证码 换一张
取 消