Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind arguments to a C function pointer?

I have done some research about how to use function pointers in C and I was trying to do some model of an object-oriented kind of thing. So to model such a thing I have been told I would have to add function pointers to the structs, so that they would be kind of 'an object'.

As I am pretty new on programming in C, this question may seem a little stupid (or very easy to answer), but on the Internet, I just found examples concerning C++ and that's not what I am searching.

Here is an example I would like to show, so that you can easily understand what my question is about:

try.h-file:

struct thing {
  void (*a)(int, int);
};
void add(int x, int y);

try.c-file:

#include <stdio.h>
#include <stdlib.h>
#include "try.h"

void add(int x, int y) {
  printf("x + y = %d\n", x+y);
}

int main(int argc, char* argv[]) {
  struct thing *p = (struct thing*) malloc(sizeof(struct thing));
  p->a = &add;
  (*p->a)(2, 3);
  free(p);
  p = NULL;
  return 0;
}

As an example I would want to have always x = 2, so the function pointer in struct thing would be this kind of pointer: void (*a)(int) and not void (*a)(int, int) anymore.

How can I bind the argument x = 2 when passing the function pointer to the struct (line p->a = &add;)? Is this even possible in C? In C++ I have seen something like std::bind, but I wasn't able to do this in C.

like image 885
user2399267......seems good Avatar asked Oct 03 '22 17:10

user2399267......seems good


1 Answers

The function pointer has to have the same signature (type and arguments) as the function it points to, so you can't really do it like that.

You could wrap the bind and the call in another couple of functions:

struct thing {
  void (*a)(int, int);
  int x;
};
...
void bind1st( struct thing *p, int arg )
{
  p->x = arg;
}

void call( struct thing *p, int arg )
{
  p->a( p->x, arg );
}

You'll want to experiment with this a bit, but that should get you started.

like image 167
John Bode Avatar answered Oct 11 '22 07:10

John Bode