开发者

Function pointer techniques for wrapping arbitrary functions in c

开发者 https://www.devze.com 2023-03-01 13:28 出处:网络
In c there is a very easy way to wrap a function(for timing/logging/etc) with a macro #define WRAP(func,args) \\

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 i开发者_开发知识库t 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.


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.


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...


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")


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消