简体   繁体   中英

How can I correctly assign a pointer to a call back function?

I try to call a function in a IRQ with C, with the next code I get it.

static void (*functionPulsacion)();

void eint2_init(void *funcPulsacion){
    functionPulsacion = funcPulsacion;
}

But when I compile in Keil the IDE show me the next message:

Button2.c(38): warning: #513-D: a value of type "void " cannot be assigned to an entity of type "void ( )()"

What is the good way for do this?.

Thank you in advance

Make sure the type of funcPulsacion matches that of functionPulsacion , like so:

static void (*functionPulsacion)(void);

void eint2_init(void (*funcPulsacion)(void)) {
    functionPulsacion = funcPulsacion;
}

It helps to use typedef to define the function pointer type so it can be reused:

typedef void (*functionPulsacion_type)(void);

static void functionPulsacion_type functionPulsacion;

void eint2_init(functionPulsacion_type funcPulsacion) {
    functionPulsacion = funcPulsacion;
}

It's the same syntax for the parameter variable as for the static one.

static void (*functionPulsacion)(void);

void eint2_init(void (*funcPulsacion)(void)) {
    functionPulsacion = funcPulsacion;
}

Typedefs make function pointers a lot more readable, though.

typedef void (*PulsacionFunc)(void);

static PulsacionFunc pulsacion_func;

void eint2_init(PulsacionFunc a_pulsacion_func) {
   pulsacion_func = a_pulsacion_func;
}

This is the type of a pointer to a variadic function that returns void .

static void (*functionPulsacion)();

The argument to this function, however, is void *

void eint2_init(void *funcPulsacion){
    functionPulsacion = funcPulsacion;
}

Funny thing is, with any data pointer, you could assign a void * without any issues

void foo(void *vp)
{
    int *ip = vp;
}

void bar(void *vp)
{
    char *cp = vp;
}

but according to the standard, not to a function pointer

void nope(void *vp)
{
    void (*fp)() = vp; // this might be a problem!
}

Any data pointer can be cast to a void * and back again, without even a warning. But that is data pointers; not function pointers. I belive that POSIX says that you can assign between void * and function pointers, but the C standard does not.

You can cast between function pointers, though.

Of course, that is dangerous, because once you call the function it doesn't care what type you think it has; it will do its thing according to what type it knows it has. So, it is best just to use the right pointer type here.

void yeah(void (*arg)())
{
    void (*fp)() = arg;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM