Add a parameter to a function pointer - c

I'm using a function pointer to delegate states in C.
// states
void state1(int first, int second) {
...
}
void state2(int first, int second) {
...
}
// state pointer
void (*current_state)(int, int);
// state logic
if (condition1) {
current_state = &state_1;
} else if (condition2) {
current_state = &state_2;
}
// do the thing
(*current_state)(1, 2);
Now I'm at a point where the given arguments no longer suffice, so there is a third argument needed. Since I don't want to change all states, I wondered if it is possible to pass a quasi constant parameter along with the pointer. Something like this:
void state3(int first, int second, int third) {
...
}
// state logic
...
else if (condition3) {
// calculate the constant third argument
int param3 = 0;
current_state = &state_3(int, int, param3);
}
I there a way to get this to work?

Well I'm not sure I'd recommend it but you could do this sort of thing:
#include <stdlib.h>
#include <stdio.h>
typedef int pfun();
int alice( int a, int b) { return b; }
int bob( int a, int b, int c) { return c; }
int main( )
{
pfun* f;
f = alice;
printf( "%d\n", f( 1, 2, 3));
f = bob;
printf( "%d\n", f( 1, 2, 3));
return EXIT_SUCCESS;
}
This compiles with
gcc -o funp -Wall funp.c
without warnings and runs correctly.
The point is that a function declaration like
int f();
Says that f is a function that returns an int, with unspecified arguments. The downside is that the compiler cannot check that the arguments are of the correct type.

You could pass a *void pointer and cast it to the concrete type in the state function. All state functions will have the same signature. Something like this:
// states
struct state1_args {
int first;
int second;
};
struct state2_args {
float first;
float second;
float third;
};
void state1(void* state_args) {
struct state1_args* args = (struct state1_args*)state_args;
use(args->first);
...
}
void state2(void* state_args) {
struct state2_args* args = (struct state2_args*)state_args;
use(args->third);
...
}
// state pointer
void (*current_state)(void*);
// state logic
if (condition1) {
current_state = &state_1;
current_state_args = &args_1;
} else if (condition2) {
current_state = &state_2;
current_state_args = &args_2;
}
// do the thing
(*current_state)(current_state_args);

Related

How to make a function which receive other function as param (with no known parameters)

Previously I asked How to make a function which receive a function as param in C language. I get an answer Link to the question but this solution is based on the parameters of argument's function. I mean:
int functionToPassAsParameter (int arg1, int arg2){
// do something
}
int functionWhichReceiveFunction (int (*f)(), int arg1, int arg2){
// do something
f(arg1, arg2);
// do something
}
// How to call the function
functionWhichReceiveFunction (&functionToPassAsParameter, 1, 2);
I would like something like:
int functionToPassAsParameter (int arg1, int arg2){
// do something
}
int functionWhichReceiveFunction ( f() ){
// do something
f();
// do something
}
// How to call the function
functionWhichReceiveFunction ( functionToPassAsParameter(arg1, arg2) );
So, when I call the function, I pass the correctly params but when I define the function which receive the other function I do not specify which params I will send to it. Is that possible to make?
EDIT 1:
I wanna achieve pass any function to functionWhichReceiveFunction. Something like:
int function_a (int param1, int param2) { /* Do something */ };
void function_b (char *arg1) { /* Do something */ };
// Call the function with two differents functions regardless return type nor params
int x = functionWhichReceiveFunction ( function_a(param1, param2) );
functionWhichReceiveFunction ( function_b(arg1) );
Define the function to be passed to take a void * as a parameter. That way the function that calls the given function doesn't need to know anything specific about the parameters:
struct params1 {
int arg1;
int arg2;
};
struct params2 {
char *arg1;
char *arg2;
};
int functionToPassAsParameter (void *param){
struct params1 *args = params;
// do something
}
int otherFunctionToPassAsParameter (void *param){
struct params2 *args = params;
// do something
}
int functionWhichReceiveFunction (int (*f)(void *), void *args) {
// do something
f(args);
// do something
}
struct params1 p1 = { 1, 2 };
functionWhichReceiveFunction (&functionToPassAsParameter, &p1);
struct params2 p2 = { "abc", "def" };
functionWhichReceiveFunction (&otherFunctionToPassAsParameter, &p2);
To be able to pass a function with unknown parameters to a function, declare the function that will pass the function as follows:
int g(int (*f)());
The function that is actually passed can have any number of parametes, for example:
int f(int x, void *y);
The call is now as follows:
g(f);
The above means that g passes f, which can have zero or more parameters of any type. This is denoted by the empty parameter list.
A particular function that may need to be passed is for example f.
Now g is called with function f, or any other function.
Note that it is up to g to know which parameters must be passed in calling f. So you need a "protocol" that tells g which function/type is passed. For example, besides passing the function, pass an identifier (int) that says what type of function is passed, for example:
#define fS_I_I 1 // f needs String, int, Int
#define fD_I 2 // f needs Double, Int
#define fI_I 3 // f needs Int, Int
int g(int ID, int (*f)());
g(fI_I, f);
Learn more about closures and tagged unions. Notice that C don't have them. You might want to emulate that with callbacks
I wanna achieve pass any function to functionWhichReceiveFunction
You cannot do that simply and portably. Remember that the signature of a function in C is related to its calling conventions (so to the ABI used by your compiler and your code; for examples, look into Linux x86 ABIs; so floating point arguments could be passed in different registers as integral arguments, so your compiler needs to know the signature of all your function pointers). You need to also give to functionWhichReceiveFunction something which describes the signature.
What you might consider doing, assuming your platform have function pointers of the same size and in the same address space as data pointers (this is very often the case), is to pass to functionWhichReceiveFunction a void* pointer (actually, a function pointer casted to void*) and an enumeration describing it.
For example
enum funsig_en {
funsig_void_to_void,
funsig_int_to_void,
funsig_int_to_double,
funsig_int_double_to_void,
};
Then, you'll have corresponding function signatures (types)
typedef void fun_void_to_void(void);
typedef void fun_int_to_void(int);
typedef double fun_int_to_double(int);
typedef void fun_int_double_to_void(int, double);
Suppose you have these static functions
static void statf_void_to_void(void);
static void statf_int_to_void(int);
static double statf_int_to_double(int);
static void statf_int_double_to_void(int, double);
You might declare
void
functionWhichReceiveFunction (void*res, enum funsig_en sigkind, void*fun, ...);
and you could use it as
functionWhichRecieveFunction(NULL, funsig_void_to_void
(void*)statf_void_to_void);
or
functionWhichRecieveFunction(NULL, funsig_int_to_void,
(void*)statf_int_to_void, 123);
or
double r = 0;
functionWhichRecieveFunction(&r, funsig_int_to_double,
(void*)statf_int_to_double, 2345);
I leave you to code that variadic functionWhichRecieveFunction. You need stdarg(3) facilities. It would include code like
va_args arglist;
va_start (arglist, fun);
switch(sigkind) {
case funsig_int_to_void: {
int a = va_arg(arglis, int);
fun_int_to_void* fptr = (fun_int_to_void*)fun;
(*fptr)(a);
return;
} // end case funsig_int_to_void
much later you'll need some va_end(arglis); near the end of your functionWhichRecieveFunction body.
Another possibility is using varargs. In the following example every function being called does its own interpretation of parameters.
#include <stdio.h>
#include <stdarg.h>
// expects 4 arguments (int, int, int, char*)
void f1(va_list args) {
int a, b, c;
char *d;
a = va_arg(args, int);
b = va_arg(args, int);
c = va_arg(args, int);
d = va_arg(args, char *);
printf("%d, %d, %d: %s\n", a, b, c, d);
}
// expects 3 ars (int, int, char*);
void f2(va_list args) {
int a, b;
char *c;
a = va_arg(args, int);
b = va_arg(args, int);
c = va_arg(args, char *);
printf("%d, %d: %s\n", a, b, c);
}
void caller(void (*f)(va_list), ...) {
va_list args;
va_start(args, f);
f(args);
va_end(args);
}
int main() {
caller(&f1, 0, 1, 3, "hello");
caller(&f2, 1, 2, "bye");
return 0;
}
Another possibility is to have caller to interpret parameters based on some type info and call a correct function call. This might be useful if you have a limited number of argument patterns and just regular functions to call:
void f3(int a, int b, int c, char *d) {
printf("%d, %d, %d: %s\n", a, b, c, d);
}
void f4(int a, int b, char *c) {
printf("%d, %d: %s\n", a, b, c);
}
typedef enum {
type1, type2
} Types;
void caller1(Types t, void (*f)(), ...) {
va_list args;
va_start(args, f);
switch (t) {
case type1: {
int a, b, c;
char *d;
a = va_arg(args, int);
b = va_arg(args, int);
c = va_arg(args, int);
d = va_arg(args, char *);
f(a,b,c,d);
break;
}
case type2: {
int a, b;
char *c;
a = va_arg(args, int);
b = va_arg(args, int);
c = va_arg(args, char *);
f(a,b,c);
}
}
va_end(args);
}
int main() {
caller1(type1, &f3, 3,2,1, "hi");
caller1(type2, &f4, 3,2,"take care");
return 0;
#Paul Ogilvie, this is the code:
int f(int x, void *y) {
return x;
};
int g(int (*f)()) {
int x = f(1, NULL); // call f with parameters
printf("X is: %d", x);
return(x); // return result
};
int main()
{
//g( f(1, 2) ); // this passes the result of a call to f, not f
g( f ); // this passes f
return 0;
}

Parameter passing multiple values using void pointer

I want to pass multiple arguments to a function using a void pointer.
void* function(void *params)
{
//casting pointers
//doing something
}
int main()
{
int a = 0
int b = 10;
char x = 'S';
void function(???);
return 0;
}
I know that I have to cast them to a certain variable in my function but I do not know how I can pass my 3 arguments as one void pointer to my function.
I have searched for this problem know quite some time but I could not find anything that would help me.
You could do it like this:
struct my_struct
{
int a;
int b;
char x;
}
void * function(void * pv)
{
struct my_strcut * ps = pv; /* Implicitly converting the void-pointer
/* passed in to a pointer to a struct. */
/* Use ps->a, ps->b and ps->x here. */
return ...; /* NULL or any pointer value valid outside this function */
}
Use it like this
int main(void)
{
struct my_struct s = {42, -1, 'A'};
void * pv = function(&s);
}
Following up on the OP's update:
struct my_struct_foo
{
void * pv1;
void * pv2;
}
struct my_struct_bar
{
int a;
int b;
}
void * function(void * pv)
{
struct my_strcut_foo * ps_foo = pv;
struct my_struct_bar * ps_bar = ps_foo->pv1;
/* Use ps_foo->..., ps_bar->... here. */
return ...; /* NULL or any pointer value valid outside this function */
}
Use it like this
int main(void)
{
struct my_struct_bar s_bar = {42, -1};
struct my_struct_foo s_foo = {&s_bar, NULL};
void * pv = function(&s_foo);
}
The void* is used as a pointer to a "generic" type. Hence, you need to create a wrapping type, cast convert to void* to invoke the function, and cast convert back to your type in the function's body.
#include <stdio.h>
struct args { int a, b; char X; };
void function(void *params)
{
struct args *arg = params;
printf("%d\n", arg->b);
}
int main()
{
struct args prm;
prm.a = 0;
prm.b = 10;
prm.X = 'S';
function(&prm);
return 0;
}

Access struct member by an argument of function in C

int f(){
struct NUMBER {
int A;
int B;
};
struct NUMBER *num = malloc(sizeof(struct NUMBER));
num->A = 1;
num->B = 2;
int x = num->B;
return x;
}
int main(){
int z = f();
printf("%d\n", z);
}
Obviously, ./a.out will show 2.
My question: Can I access struct member by an argument of function? i.e. f(A) return 1, and f(B) return 2. Thanks a lot.
Not at all elegant, but I think it shows you what you need to do/know.
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
struct NUMBER {
int A;
int B;
};
struct NUMBER extNumber = {1, 2};
int f(int offset) {
int iRet = -1;
if (offset == offsetof(struct NUMBER, A)) {
iRet = extNumber.A;
} else if (offset == offsetof(struct NUMBER, B)) {
iRet = extNumber.B;
}
return iRet;
}
int main (int argc, char **argv) {
struct NUMBER number;
int iVal;
iVal = f(offsetof(struct NUMBER, A));
printf ("A : %d\n", iVal);
iVal = f(offsetof(struct NUMBER, B));
printf ("B : %d\n", iVal);
}
Can I access struct member by an argument of function?
I think you are also assuming struct is not visible outside the function. Now if the person who wrote main does not have visibility into the function (say it is part of a library), then the answer is NO.
Otherwise if author of main can see internals of the function, then: Can someone come up with a fancy way to access struct member inside the function via function argument? Towards that lets think what does f(A) mean? Here, A is a name of struct member, so do you mean passing char A to f and translating that to struct member inside f [e.g. result = *(int *)num+(inchar-'A') where inchar is aninput parameter to the function of type char]. Similarly, one can imagine other ways.
As far as I understand your problem, the cleanest and most "C-like" solution is to pass a pointer to your struct to f(), where you populate it:
typedef struct _NUMBER
{
int A;
int B;
}
NUMBER;
void f (NUMBER* pvNumber)
{
pvNumber->A = 1;
pvNumber->B = 2;
return;
}
Call it like this:
int main ()
{
NUMBER vNumber;
int z;
f (&vNumber);
z = vNumber.A; // or vNumber.B
return 0;
}
So you don't select the desired member inside f(), but outside of it.
Yes. you need to define some way to access to member desired, this is usually done with constants, or an enum. As an aside, you should always check the pointer returned by malloc() before using it.
#define GET_A (0)
#define GET_B (1)
int f(int selector){
struct NUMBER {
int A;
int B;
};
int result;
struct NUMBER *num = malloc(sizeof(struct NUMBER));
if (!num)
return -1; // or some other error code...
num -> A = 1;
num -> B = 2;
switch(selector)
{
case GET_A: result = num->A; break;
case GET_B: result = num->B; break;
// etc... if you have more members in your struct.
default: result = -1; break; // some error code.
}
free(num)
return result;
}
int main(){
int z = f(GET_B);
printf( "%d\n" , f(GET_B));
}

How do I declare a function that returns a function pointer?

Imagine a function myFunctionA with the parameter double and int:
myFunctionA (double, int);
This function should return a function pointer:
char (*myPointer)();
How do I declare this function in C?
typedef is your friend:
typedef char (*func_ptr_type)();
func_ptr_type myFunction( double, int );
void (*fun(double, int))();
According to the right-left-rule, fun is a function of double, int returning a pointer to a function with uncertain parameters returning void.
EDIT: This is another link to that rule.
EDIT 2: This version is only for the sake of compactness and for showing that it really can be done.
It is indeed useful to use a typedef here. But not to the pointer, but to the function type itself.
Why? Because it is possible to use it as a kind of prototype then and so ensure that the functions do really match. And because the identity as a pointer remains visible.
So a good solution would be
typedef char specialfunc();
specialfunc * myFunction( double, int );
specialfunc specfunc1; // this ensures that the next function remains untampered
char specfunc1() {
return 'A';
}
specialfunc specfunc2; // this ensures that the next function remains untampered
// here I obediently changed char to int -> compiler throws error thanks to the line above.
int specfunc2() {
return 'B';
}
specialfunc * myFunction( double value, int threshold)
{
if (value > threshold) {
return specfunc1;
} else {
return specfunc2;
}
}
Make a typedef:
typedef int (*intfunc)(void);
int hello(void)
{
return 1;
}
intfunc hello_generator(void)
{
return hello;
}
int main(void)
{
intfunc h = hello_generator();
return h();
}
char * func() { return 's'; }
typedef char(*myPointer)();
myPointer myFunctionA (double, int){ /*Implementation*/ return &func; }

abstract function pointers

How would I create an array of ten function pointers? What I have is a for loop, and I want to set a function pointer to a different function on each iteration. so:
//pseudocode
for i (0..10)
function = array_of_functions[i];
//...
// Define alias for function pointer type for convenience
typedef void (*action)(int);
// Example function
void print(int) { ... }
action fs[10] = { print, ... };
for (int i = 0; i < 10; ++i)
{
action f = fs[i];
// Call it somehow
f(i * i);
}
This code:
return_t (*array_of_functions[10])(arg1_t, arg2_t);
Declares "array_of_functions" as a 10-element array of function pointers where each pointed-to function takes two arguments of type arg1_t and arg2_t and returns type return_t. Replace types and adjust the number of arguments as appropriate.
Any time you have to deal with ugly function pointer syntax it's better to use a typedef.
#include <iostream>
void a(int i)
{
std::cout<<"a: "<<i<<std::endl;
}
void b(int i)
{
std::cout<<"b: "<<i<<std::endl;
}
typedef void (*fn)(int);
int main(int argc, char**argv)
{
fn foo[2];
foo[0] = a;
foo[1] = b;
for(size_t i = 0; i < sizeof(foo) / sizeof(foo[0]); ++i)
{
foo[i](i);
}
return 0;
}
The simplest way to do it is to create a typedef for your function, and then declare an array with that type. To create a typedef for the function: typedef returntype (*typedefname)(argtype1,argtype2,...,argtypeN); EX:
#include <stdio.h>
#include <stdlib.h>
typedef void (*functype)();
void func1()
{
//...
}
void func2()
{
//..
}
//...
void func10()
{
//...
}
int main(int argc, char* argv[])
{
functype array[] =
{
&func1,
&func2,
&func3,
&func4,
&func5,
&func6,
&func7,
&func8,
&func9,
&func10
};
// Use the array...
return 0;
}
T (*array_of_functions[10])();
Where T is the return type of each function (all functions return the same type, naturally). Things get tricky if you want to store pointers to functions with different numbers/types of parameters:
int foo(void) {...}
int bar(int x) {...}
int bletch(double y, double z) {...}
...
int (*array_of_functions[10])() = {foo, bar, bletch, ...};
If so, you'll have to keep track of what number and types of parameters each function requires somehow so you can call it correctly.
I'm actually kind of down on typedefs for function pointer types; they tend to obscure as much as they simplify.

Resources