Reputation: 2699
I'm running in a little issue here, I've got this function pointer :
typedef void* (* funcPointer)(const void *in, int ilen, void *out, int *olen)
And this function
void* foo1(const void *in, int ilen, void *out, int *olen)
{
if(CONST_VALUE_1 > iLen)
//do something
else
//do something else
return whatever;
}
Somewhere in the code
// ...
funcPointer fpointer = foo1;
if(someArgument > SOME_OTHER_CONSTANT)
// where foo2 is the same as foo1 except that it uses CONST_VALUE_2
fpointer = foo2;
bar( someVariable, anotherVariable, fpointer);
// ...
As you can see, there is a CONST_VALUE_X
in the body of this function. I would like to be able to remove the constant and use a fifth argument instead. Since I can't modify the signature, I was wondering if there was something to do or copy-paste the function with every possible constant value...
Thank you
Upvotes: 4
Views: 332
Reputation: 215287
What you want is called a closure, and C does not have explicit support for closures. You can achieve the same thing by modifying your API to carry around a function pointer and argument pointer instead of just a function pointer. Then you just need to versions of the function: one that uses the explicit caller-provided argument, and another that uses a value from the carried argument pointer.
Upvotes: 0
Reputation: 26114
You could replace the constant with something that the caller can temporarily change (like a global variable).
For example:
int oldLenghtLimit = LengthLimit;
... call the function ...
LengthLimit = oldLengthLimit;
And, in the function:
void* foo1(const void *in, int ilen, void *out, int *olen)
{
if(LengthLimit > iLen)
//do something
else
//do something else
return whatever;
}
Upvotes: 0
Reputation: 272557
If you can't modify the function signature, then as you say, you won't have a fifth argument!
I see three options:
I guess you could shoehorn it into one of the other void *
arguments (e.g. define a struct that contains the original value for in
, and the "constant" value, and then pass this in as in
).
Set a global variable before calling the function. This is a bad idea.
You could write this function as a macro, to avoid the copy-and-paste maintenance nightmare. This is a bad idea.
Upvotes: 1