Home > Enterprise >  Call a function using a pointer and pass it along in the parameters
Call a function using a pointer and pass it along in the parameters

Time:05-15

Say that I have a pointer to function theFunc. theFunc takes along a pointer that points to the address where theFunc is stored (it takes a function pointer). Is this possible?

Using it would look like this:

funcPtr(funcPtr);

That calls the function pointed to by funcPtr, and then passes along the address contained in the pointer. I do not want to use void pointers because I want to change the function pointed to by funcPtr.

CodePudding user response:

You cannot simply typedef a function type that accepts itself as a parameter. I.e. something like this will not work:

/* Will cause a compilation error, MyFuncType used a parameter is not yet defined: */
typedef void(*MyFuncType)(MyFuncType);  

However - you can still use a void* to achieve what you want. The typedef is using void*, but inside the function you can cast it to your function pointer type, modify it and call it.

See here:

typedef void(*MyFuncType)(void*);

void f(void* pF)
{
    if (pF)
    {
        MyFuncType ff = (MyFuncType)pF;
        /* Change ff here if you need. */
        /* Call it: */
        ff(0);
    }
}

int main()
{
    f(f);
    return 0;
}

Update:
Following the comment from @JosephSible-ReinstateMonica below, I added a 2nd solution. It does not involve a cast between data and function pointers, but it requires another typedef and a cast when calling f with itself:

typedef void(*FuncType1)(void);
typedef void(*MyFuncType)(FuncType1);

void f(MyFuncType pF)
{
    if (pF)
    {
        /* Change pF here if you need. */
        /* Call it: */
        pF(0);
    }
}

int main()
{
    f((MyFuncType)f);
    return 0;
}

CodePudding user response:

Yes, it's possible. Example code with void as return type:

#include <stdio.h>

void theFunc(void (*funcPtrArg)())
{
    if(funcPtrArg!=NULL) 
    {
        printf("this is theFunc(...) with %s as argument\n",funcPtrArg?"a function pointer":"NULL");
        funcPtrArg(NULL);
        return;
    }
    printf("this is theFunc(...) with %s as argument\n",funcPtrArg?"a function pointer":"NULL");
    return;
}

int main()
{
    void (*funcPtr)() = theFunc;
    funcPtr(funcPtr);
    return 0;
}
  • Related