Kamath
Kamath

Reputation: 4664

Generic function pointer in C

I am writing a generic test function that will accept a function address (read from a map file) and arguments as comma separated data as arguments from a socket.

I am able to implement it for known function pointers.

like

void iif(int a, int b, float f);
typedef void (*fn_t)(int a, int b, float f);

With above approach I would write function pointers for all types of function implementation in the code base. Is there any generic way to do this?

Upvotes: 2

Views: 411

Answers (2)

unwind
unwind

Reputation: 399763

No, since the compiler needs to know how to represent the arguments. It can't know that for a function pointer type that excludes the information, and thus it can't generate the call.

Functions with a small number of parameters might pass them in CPU registers, "spilling over" to the stack when many parameters are called for, for instance.

You can use varargs to come around this, doing so essentially "locks down" the way the arguments are passed. Of course, it forces the called functions to deal with varargs, which is not very convenient.

Upvotes: 4

Burak Tamtürk
Burak Tamtürk

Reputation: 1239

You can do the following.

fn_t fncptr;
fncptr= MapAddress + 0x(offset);

MapAdress is where you map file to memory address. (You can cast to DWORD before, if C++ compiler fails to add offset to void) Offset is where the function code in file. But rememder, you will need exetuce address to pointer in windows is PAGE_EXETUCE_READWRITE. ThenCall it like,

fncptr(arg1, arg2, arg3);

if compiler fails in first code, do this: fn_t fncptr; fncptr= (fn_t)((DWORD)MapAddress + 0x(offset));

Upvotes: 0

Related Questions