Bobi.Liu
Bobi.Liu

Reputation: 321

Is that possible to modify a function pointer in C language?

I have a function A(int num) now. I want to get another function B(int num), which runs another function C() before executing A(num). What I intend to write is like

typedef void (*function_type)(int); 

function_type attachToFunction(function_type original, void (*additional_function)(void))
{
    /* return a function_type which first runs additional_function, and then runs original(int) */
}

However, I don't don't how should I finish the function or if it is possible.

I'm using C and C++ together, so a C++ implementation is also acceptable as long as the function declaration doesn't change.

Upvotes: 0

Views: 243

Answers (1)

Jarod42
Jarod42

Reputation: 217478

Not with a clean way.

You might use global as you cannot capture the parameters with that interface:

typedef void (*function_type)(int); 

static function_type g_original = 0;
static void (*g_additional_function)() = 0;

void my_function(int n)
{
    if (g_additional_function) g_additional_function();
    if (g_original ) g_original(n);
}

function_type attachToFunction(function_type original,
                               void (*additional_function)(void))
{
    g_original = original;
    g_additional_function = additional_function

    return my_function;
}

Because of the global, you can have only one of that "attached" function at a time.

In C++, you can "capture" the function pointer via template. Those parameter should be compile-time though

template <function_type f, void (*g)()>
void funcT(int n)
{
    g();
    f(n);
}

Usage would be similar to

void C();
void A(int b);

void (*B)(int) = &funcT<&A, &C>;

Upvotes: 1

Related Questions