Changing a Function Pointer Signature

I have a little problem here, I have this function:

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, the body of this function has CONST_VALUE_X . I would like to be able to remove the constant and use the fifth argument instead. Since I cannot change the signature, I was wondering if I need to do something or copy-paste a function with any possible constant value ...

thanks

+4
source share
3 answers

If you cannot change the signature of the function, then, as you say, you will not have the fifth argument!

I see three options:

  • I think you could train it with one of the other void * arguments (for example, define a structure that contains the original value for in and a value of "constant", and then pass this as in ).

  • Set the global variable before calling the function. It is a bad idea.

  • You can write this function as a macro to avoid a nightmare that supports copying and pasting. It is a bad idea.

+1
source

You can replace the constant with what the caller can temporarily change (for example, a global variable).

For instance:

 int oldLenghtLimit = LengthLimit; ... call the function ... LengthLimit = oldLengthLimit; 

And in function:

 void* foo1(const void *in, int ilen, void *out, int *olen) { if(LengthLimit > iLen) //do something else //do something else return whatever; } 
0
source

What you want is called closure, and C does not have explicit support for closures. You can achieve the same by changing your API to carry a function pointer and an argument pointer instead of a function pointer. Then you just need versions of the function: one that uses the explicit argument provided by the caller, and another that uses the value from the pointer of the transferred argument.

0
source

All Articles