1

In c there is a very easy way to wrap a function(for timing/logging/etc) with a macro

#define WRAP(func,args) \
...
func args /*call function with args num of args irrelavent*/         \
...

WRAP(some_func,(arga_a,arg_b)) since it expands to "func (args)"

But eventually you get tired of the drawbacks of macros.

Is there any way to do this in a simple fashion with a function taking a function pointer? It is important that it fits a function with any number of arguments(well we can say less then 7 if it supports 0-6 arguments. and without change to the function.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Roman A. Taycher
  • 18,619
  • 19
  • 86
  • 141
  • I'm wondering if C is the most practical language for that sort of things. – Alexandre C. Apr 27 '11 at 11:13
  • c is the language in use at work(and it is somewhat suited for the purpose at hand) and I use it to cut severely on verbosity. macro have a lot of problems though and are discouraged. – Roman A. Taycher Apr 27 '11 at 11:18

4 Answers4

2

In C, no. There is no way to declare or call an "arbitrary" function pointer (i.e. one with an arbitrary prototype).

The best you could do is use variadic functions.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
2

I don't think you can have a variadic function pointer. A possible solution is to use a function pointer which take a "cookie" argument that you can use to pass your own structure having all required field.

The prototype will be as follow:

void (myFunc*)(void * cookieP);

But this has the drawback to loose the typing of function arguments and you will require to cast the parameter...

greydet
  • 5,509
  • 3
  • 31
  • 51
1

Looks similar to this question: Either keep using MACROS, or pass all your extra args through a structure (thus turning your function into a "method")

Community
  • 1
  • 1
hugomg
  • 68,213
  • 24
  • 160
  • 246
0

How about good old void* ?

#include<stdio.h>

int bla(int a){ //some random function
  return a+1;
}

int main(){
  void* ptr; //void* aka universal pointer
  int lol; //result goes here
  ptr = &bla; //pointer to function
//return_value = ( (cast_to_function_type) (pointer_to_function) )  (argument_or_arguments);
  lol = ( (int(*)(int)) (ptr) )  (1);
  printf("%d\n", lol); //print the result
  return 0;
}
bool.dev
  • 17,508
  • 5
  • 69
  • 93
  • Why not use a function pointer instead of a cast? But more importantly, what's the point of this code snipped? I can't see what it adds to a simple direct function call. – Alexey Frunze Sep 29 '12 at 06:32
  • Casting a `void*` to a function pointer is undefined behavior, this isn't a good way to do this. – porglezomp Feb 04 '17 at 19:56