Python-like function decorators in C - c

I'm trying to implement a Python-like function decorator in C using function pointers but I'm getting weird segmentation fault error.
Idea is that we have a decorator function which has inner function wrapper. Decorator then takes some_function as an argument, puts it inside the wrapper along with additional code and returns the wrapper function.
Very simple function decorator in Python:
def decorator(f):
def wrapper():
#do something before
f()
#do something after
return wrapper
def some_func():
print('Hello')
some_func = decorator(some_func)
I know that Python, unlike C, treats functions as first class objects but I'm wondering if the same sort of functionality can be emulated in C by using function pointers.
I tried this
void* do_twice(void (*func)())
{
auto void wrapper()
{
func();
func();
}
return &wrapper;
}
void some_func()
{ printf("Hello\n"); }
int main()
{
void (*fun_ptr)() = &some_func;
fun_ptr = decorator(fun_ptr);
fun_ptr();
return 0;
}
Output
Hello
Segmentation fault
Now here is the funny bit. If I declare a variable inside wrapper like this:
auto void wrapper()
{
int blah=5;
func();
func();
}
Then segmentation fault is fixed. Can someone explain why is this so? Apparently I'm doing something wrong with the pointers and code is very unstable - seemingly unrelated additions to the main function will cause segmentation fault to pop again.

Do you allow me to have an excursion to C++? In this language, there are functor objects, these are kind of structs that can be called like a function:
struct Wrapper
{
/* this is what allows the struct to be called like a function: */
void operator()(/* can define arbitrary parameters here */)
{ /* some implementation */ }
};
In other words, this would allow you to write code like:
Wrapper w; // actually, C++ does more here than C, but that's out of
// scope of this question...
w(); // possible due to the operator() defined above
OK, now let's extend that a bit:
struct Wrapper
{
void(*m_f)(void); /* !!! */
void operator()(void) /* don't want any parameters... */
{
printf("before\n");
m_f();
printf("after\n");
}
};
Don't want to go any deeper, a C++ developer would now deal with accessibility (such that the member m_f can only be used inside the class) and would provide a so-called constructor (for initialising m_f member appropriately). With all that, the final C++ code using the wrapper class might look like:
Wrapper decorate(void(*f)(void))
{
return Wrapper(f); // the fore-mentioned constructor gets called
}
void test(void) { /* do something */ }
void demo(void)
{
Wrapper w = decorate(&test);
w();
}
Why that excursion? Well, have a close look at one specific line:
void(*m_f)(void);
Yes, there is a member variable! Python actually does something similar internally.
The 'problem' with C is that you cannot define your own function call operators. There's only the native one. So the big question is: Where to store the function pointer?
You could have a struct, storing the function pointer (analogously to the C++ solution), and pass that one to your own function emulating the function call operator. Actually, the C++ solution doesn't do anything else either, solely that all this is hidden behind syntactic sugar!
An equivalent C solution might look like this:
struct Wrapper
{
void(*m_f)(void);
};
void executeDecorated(Wrapper w)
{
printf("before\n");
w.m_f();
printf("after\n");
}
void demo(void)
{
Wrapper w = { &someFunction };
executeDecorated(w);
/* do whatever else ... */
executeDecorated(w);
}
This is probably the closest you can get in C (apart from that you might perhaps find better names).
If having a separate struct to store a function pointer brings you sufficient benefit or if you just want to pass the function pointer directly (executeDecorated(&someFunction), assuming the function was adjusted appropriately) is up to you to decide...

Related

How to obtain the function name and number of arguments from a function in C?

Lets say I am maintaining an array of function structures in which I store API information.
This is definition of function structure:
typedef struct function {
void (*func)(long, ...);
char* name;
int argc;
char *argv[];
} function;
function api_list[N]
I would maintain a list of such structures.
Now given any function, I want to write a function Register(api_list, fp)
which adds one such structure initialized with details of function fp.
int fp(int a, int b) {
return a+b;
}
Register(api_list, fp);
How to do it in C?
I believe you will need to either parse the C function declarations yourself or find some other code to do it. I looked around a bit and there's code for this in the Ruby FFI, PerlXS and other script binding generators like SWIG. I also saw the XML plugin to GCC which generates XML describing the program.
If you look up C's BNF or EBNF definitions and know a bit of parsing theory, figuring out C functions is not hard. C++ is a whole other ball o' wax.
Note: I think I misunderstood. The following is for calling C functions with unknown number and types of arguments. Not for finding out what the function signature already looks like.
Look at the FFI (Foreign Function Interface) library which can be found at Sourceware:
https://sourceware.org/libffi/
This is packaged with many Linux systems already because it is heavily used by interpreted languages that need to call C functions.
Now given any function, I want to write a function Register(api_list, fp) which adds one such structure initialized with details of function fp.
There is no way to do this in Standard C. The main reason is you need keep track of original definition of an function to call it via such structure. You actually could store every function pointer as struct member:
void (*func)()
that is fine, but any attempt to call such function when type is not compatible (both parameters and return type are not the same) with original definition will invoke undefined behaviour. This means, that you would need to cast it properly for every call:
((int (*)(int, int)) api_list[0])(1, 2);
You may use GCC extensions typeof, but this method requires writing function's name (here fp) explicitely:
int result = ( (typeof(fp)*) api_list[0].func)(1, 2);
Even if you have stored somehow character string "fp" inside name member, there is no way to "connect" it with typeof, since it does not take string literals (well it takes, but not in the way you want) and in general there is no way to have it "destringized" as fp token.
Here is an illustration of above concepts:
#include <stdio.h>
typedef void (*GENERIC_FUNC_PTR)();
typedef struct function
{
GENERIC_FUNC_PTR func;
} function;
void Register(function *api_list, GENERIC_FUNC_PTR func)
{
api_list->func = func;
}
int add(int a, int b)
{
return a + b;
}
void print_message(void)
{
printf("%s\n", __func__);
}
int main(void)
{
function api_list[10];
Register(api_list, (GENERIC_FUNC_PTR) add);
Register(api_list + 1, (GENERIC_FUNC_PTR) print_message);
printf("%d\n", ( (typeof(add)*) api_list[0].func)(1, 2));
( (typeof(print_message)*) api_list[1].func)();
return 0;
}

Call flow for the code - C

I am looking into some C code for a microcontroller. I understand most of the code however this piece of the code is puzzling me.
I am also including relevant definitions for used data types. I have substituted function and variable names for the ease sake.
#define COUNT (2)
typedef void(*some_type)(void *p);
some_type some_arr[COUNT] = {NULL, };
void init(void)
{
first_function(&second_function);
}
void first_function(some_type cb)
{
if(some_arr_count < COUNT)
{
some_arr[some_arr_count++] = cb;
}
}
void second_function(void *p)
{
another_type *req;
req = (another_type *)p;
//some other code goes here
}
1.What does this typedef means?
typedef void(*some_type)(void *p);
init() function gets called only once and it has only one line of code.
2.What does this line do?
first_function(&second_function);
I searched for the term second_function in the entire project code and it this the only place it appears besides function definition.
3.So how does second_function get called?
The following typedef
typedef void(*some_type)(void *p);
will define some_type as a pointer to function of type void ()(void *).
The following statement
first_function(&second_function);
is a function call, &second_function, which is the address of second_function , is the argument to first_function().
The function second_function could be called like this
some_arr[some_arr_count](p);
some_arr[some_arr_count] is a function pointer to second_function, which is assigned in first_function, and p is the argument of second_function, which is a pointer to void.
Firstly, as suggested in the comments you should go read about function pointers. I got this (How do function pointers in C work?) from a Google search.
The above link should help to explain answers to question 1 and 2. For question 3, it is likely that the micro-controller has some built-in mechanism or library function which calls all the function call-backs in some_arr[COUNT], something like the following might work (untested):
for (int i = 0; i < COUNT; ++i)
{
if (some_arr[i] == NULL) break;
(*some_arr[i])(&something_useful);
}
Where something_useful would be some sort of data that the call-back function could use.
If you are able to search the library code for uses of some_arr you might find code to call the second_function (although it will no longer be called second_function).

defining an array of C functions

I've got a bunch of C functions which get assigned to an array of function pointers, along the lines of this:
typedef int (*func)(int);
int SomeLongName1(int a) {
// ...
}
// ...
int SomeLongName1000(int a) {
// ...
}
func f[] = { SomeLongName1, ... , SomeLongName1000 };
This is a lot of work to create and is prone to errors. For instance, there could be a typo in the function name such that a valid function is still named, but the wrong one. Or, if a new function is added at the end one could forget to go in and explicitly add it to the list of function pointers as well.
In order to avoid having to explicitly declare the array of function pointers I have tried various tricks such as macros, which make the code hard to understand and require knowing how the macro works, and I am generally unsatisfied with them.
What I would like to do is something like this:
typedef int (*func)(int);
func f[] = {
int SomeLongName1(int a) {
// ...
}
// ...
int SomeLongName1000(int a) {
// ...
}
};
This way, the array would be automatically created, and if there was some way to put a null pointer at the end so I can determine how many function pointers there are that would be great as well.
However, the above isn't valid C and I'm coming up empty with any way of accomplishing this. If it is something compiler specific (e.g. a GCC extension) that would be ok.
All the functions are statically known at compile time, so I would like to avoid having to do any run-time initialization of the function pointer array - not that I have found a method to do it that way either.
This related question How to define an array of functions, seems to ask the same question, but does not carry it to its logical conclusion. Specifically, I don't want to have to re-type anything I have already typed so as to save time and avoid errors.
If you don't care about the order of functions in the array, and are willing to use a GCC extension, then you can achieve what you want using a whole bunch of initializer (constructor) functions. This obviously isn't ideal because of the sheer number of extra functions defined, but it is certainly one approach you can consider. It constructs the array at runtime.
Define the function append to append a single function to an array (reallocating if needed). Then, the code is basically
#define ARRAYFUNC(name) int name(int); \
void __attribute__((constructor)) __init_##name(void) { append(func); } \
int name(int a)
ARRAYFUNC(func1) {
...
}
ARRAYFUNC(func2) {
...
}
You could use the C preprocessor (X-Macros) for this:
#include <stdio.h>
// define a list of function names and bodies
#define FUNCS \
FUNC(add, { return a+b; }) \
FUNC(mul, { return a*b; }) \
FUNC(div, { return a/b; })
// let the preprocessor make up the actual function implementations
#define FUNC(name, body) int name(int a, int b) body
FUNCS
#undef FUNC
typedef int (*func)(int, int);
// let the preprocessor populate the array of function pointers
func f[] = {
#define FUNC(name, body) name,
FUNCS
#undef FUNC
};
// use it:
int main () {
int a = 2, b = 3, i = 0;
for (; i < sizeof(f)/sizeof(*f); i++) {
printf("%d\n", f[i](a,b));
}
return 0;
}
The output is:
$ gcc test.c && ./a.out
5
6
0
What I would use to solve such a situation (only if I can't avoid it, of course), is to use preprocessing. Not the one available from the C preprocessor, it does not provide the required functionality in a sensible syntax, but a really powerful one like m4.
With m4, your code could look like this:
define(`functionList', `, 0')
define(`functionArrayMember', `define(`functionList', `$1, 'FunctionList)$1')
define(`buildFunctionArray', `{ functionList }')
int functionArrayMember(SomeLongName1)(int a) {
return a+1;
}
//...
int functionArrayMember(SomeLongName1000)(int a) {
return a+1;
}
func f[] = buildFunctionArray();
You just need to provide the right m4 definition for functionArrayMember() and buildFunctionArray(), and you have the functionality you need.
I do not think there is any other way of doing what want to do.
What you wrote
func f[] = { SomeLongName1, ... , SomeLongName1000 };
already does what is best.
Maybe you could name your functions with an prefix 0000 to 1000, so that you can be sure each function is in the right place in your functions pointer array.
Also, if you really have 1000 different functions, they are surely things in common that could lead you to sort them in several arrays, reducing the numbering effort, and that is less error prone.

Pointer to a function that takes a pointer to another function as argument

This should be a simple question, but I might not be able to word it correctly or I might be trying to defy the principles of the C language because of my lack of experience with it.
All I want to do is, given a pointer to a function, to wrap it inside another function that takes a pointer to a function as an argument, and make a pointer of the later. Better in code:
void do_nothing_1() {}
void do_nothing_2() {}
void wrapper(void(*f)()) { f(); }
int main() {
// the following will call the function
// but i just want a pointer of whats being called
funcion_pointer_1 = wrapper(do_nothing_1);
funcion_pointer_2 = wrapper(do_nothing_2);
return 0;
}
I apologize beforehand if the question doesn't make any sense, please help me clarify it rather than simply downvote it.
Edit: Given the apparent difficulty to obtain the results desired because of the obscurity of the requirements, I will be a little more specific on what I am looking for.
Inside a struct, I have a pointer to a function:
struct my_struct {
int (* run)(void);
}
What I want to do is to modify that function and that's why I use the wrapper. So, for example, if foo returns void change that to int. Also, run some code before executing foo:
int wrapper(void (*foo)()) {
// exec some stuff here
foo();
return 0;
}
Ultimately, what I want is that when I execute the function corresponding to the *run pointer from my structure, execute some stuff before doing run() and change the return type.
When struggling with the correct syntax, it is helpful to use typedefs to make things clearer. Not just for yourself as you write the code, but for anyone who needs to maintain it, or just try to figure out what it's doing.
You want a function pointer to a function that takes another function pointer as an argument. Start with the argument, a function without parameters and no return value:
typedef void (*void_handler_t)( void);
And now the wrapper function pointer, one that takes a function pointer parameter and has no return value:
typedef void (*wrapper_handler_t)( void_handler void_fn);
And the code:
void foo( void) {}
void wrapper( void_handler_t wrapped_fn)
{
wrapped_fn();
}
int main( int argc, char *argv[])
{
wrapper_handler_t function_pointer;
function_pointer = &wrapper;
function_pointer( &foo);
return 0;
}

What are the different ways to call a function?

What are the different ways to call a function? For example, can I call a function without ()?
You can call by name:
function_name(args);
You can call by function pointer:
void (*function_pointer)(int, char *) = ...;
(*function_pointer)(3, "moo"); // classic function pointer syntax
function_pointer(3, "moo"); // alternate syntax which obscures that it's using a function pointer
No, you cannot call a function without using (). You can hide the () by using a macro but that just hides where they are; in the end you must use () somewhere.
You can use a macro:
#define f func()
but this is not a recommended way. Your code will be very difficult to read and understand.
In C the () is the function invocation syntax. You cannot call a function without it.
There are several pedantic ways to invoke a function without using (). Naming the function "main" (with correct parameter & return types) is one good way. You could register it as an interrupt handler. You could trick the compiler into jumping into it by smashing the stack (not portable and not recommended, works with gcc on 64-bit x86):
#include <stdio.h>
void foo()
{
printf("In foo\n");
}
void bar()
{
long long a;
long long *b = &a;
void (*fooptr)() = &foo;
b[2] = (long long)fooptr;
}
int main()
{
bar();
}

Resources