when do we use function pointers - c

I am trying to understand the existing code.
When do we actually go for function pointers? specially like the one below.
struct xx
{
char *a;
(*func)(char *a, void *b);
void *b;
}
struct xx ppp[] = { };
then check sizeof(ppp)/sizeof(*ppp);
when do we go with such kind of approach?

sizeof array / sizeof *array is a way of finding out how many elements are in an array. (Note that it must be an array rather than a pointer.) I'm not sure how that's related to your function pointer question.
Function pointers are used to store a reference to a function so that it can be called later. The key thing is that a function pointer needn't always point to the same function. (If it did, you could just refer to the function by name.)
Here's an example based on your code (although I could provide a better one if I knew what your code was supposed to do.
char *s1 = "String one";
char *s2 = "String two";
void f(char *a, void *b) {
/* Do something with a and b */
}
void g(char *a, void *b) {
/* Do something else with a and b */
}
struct xx {
char *a;
void (*func)(char *a, void *b);
void *b;
}
struct xx ppp[] = { {s1, f, NULL}, {s2, g, NULL} };
int main(int argc, char **argv) {
for (int i = 0; i < (sizeof ppp / sizeof *ppp); i++) {
ppp[i].func(ppp[i].a, ppp[i].b);
}
}

There are two major uses (that I know of) for function pointers in C.
1. Callbacks
You have some sort of event-driven framework (a GUI is one of the easiest examples), and the program wants to react to events as they happen. Now you can do that with an event pump, like
while (event *e = get_one_event()) {
switch (e->type) {
case EVT_CLICK:
...
}
}
but that gets tiring after a while. The other major alternative is callbacks. The program defines a bunch of functions to handle different events, and then registers them with the library: "when event X happens, call function Y" -- so of course, the library is going to receive a function pointer, and call it at the relevant time.
2. Objects (function tables / vtables)
If you've done OO in most other languages, this should be fairly easy for you to picture. Imagine an object as a struct that contains its members and then a bunch of function pointers (or, maybe more likely, its members and a pointer to another struct representing its class, that contains a bunch of function pointers). The function pointers in the table are the object's methods. GLib/GObject is a big user of this technique, as is the Linux kernel (struct file_operations, struct device_driver, struct bus_type, and many many more). This lets us have an arbitrary number of objects with different behavior, without multiplying the amount of code.

When do we actually go for function pointers? specially like the one below.
You use function pointer when you want to make something more abstract.
By example, suppose your application has a graphical toolbox with a certain number of buttons. Every button corresponds to an instance of a certain struct.
The button structure can contain a function pointer and a context:
typedef struct {
void (*press_button) (void *context);
void *context;
/* Here some other stuff */
} Button;
When the user clicks the button, the event is something like
void event_click (Button *b)
{
b->press_button(b->context);
}
The point in doing this is that you can use always the same structure for each button:
Button * create_button (void (*callback) (void *), void *context, /* other params */
{
Button *ret = malloc(sizeof(Button));
if (ret != NULL) {
ret->callback = callback;
ret->context = context;
/* Assign other params */
}
...
return ret;
}
So when you build your toolbox you probably do something like
Button * toolbox[N];
toolbox[0] = create_button(function1, (void *)data, ...);
toolbox[1] = create_button(function2, (void *)something, ...);
...
toolbox[N-1] = create_button(functionN, (void *)something_else, ...);
Also when you create some function pointer, always carry some contxt information (like I did with the context field of the struct). This allows you to avoid global variables, thus you can get a robust and reentrant code!
Note:
This method is awesome, but if you deal with C++ you may prefer to use object orientation and replace callbacks with derivaton from abstract classes. By doing this you also don't need to carry the context, since the class will do it for you.
Edit in answer of first comment:
The current code I am going through is related to file IO. setting an environment variable and creating symbolic links between files, copying data from one file to another, etc. I am not understanding why do we need to call these functions at run time using function pointers. we can as well call them directly.
In fact you can do what you need without using function pointers. If I do understand well your problem, you are trying to understand someone else's code, which is doing what you listed with function pointers.
Personally I don't use this feature unless I need it but if you post here some additional code maybe we can try to understand it better.

Related

Generic hashtable in C

I'm trying to create a generic hash table in C. I've read a few different implementations, and came across a couple of different approaches.
The first is to use macros like this: http://attractivechaos.awardspace.com/khash.h.html
And the second is to use a struct with 2 void pointers like this:
struct hashmap_entry
{
void *key;
void *value;
};
From what I can tell this approach isn't great because it means that each entry in the map requires at least 2 allocations: one for the key and one for the value, regardless of the data types being stored. (Is that right???)
I haven't been able to find a decent way of keeping it generic without going the macro route. Does anyone have any tips or examples that might help me out?
C does not provide what you need directly, nevertheless you may want to do something like this:
Imagine that your hash table is a fixed size array of double linked lists and it is OK that items are always allocated/destroyed on the application layer. These conditions will not work for every case, but in many cases they will. Then you will have these data structures and sketches of functions and protototypes:
struct HashItemCore
{
HashItemCore *m_prev;
HashItemCore *m_next;
};
struct HashTable
{
HashItemCore m_data[256]; // This is actually array of circled
// double linked lists.
int (*GetHashValue)(HashItemCore *item);
bool (*CompareItems)(HashItemCore *item1, HashItemCore *item2);
void (*ReleaseItem)(HashItemCore *item);
};
void InitHash(HashTable *table)
{
// Ensure that user provided the callbacks.
assert(table->GetHashValue != NULL && table->CompareItems != NULL && table->ReleaseItem != NULL);
// Init all double linked lists. Pointers of empty list should point to themselves.
for (int i=0; i<256; ++i)
table->m_data.m_prev = table->m_data.m_next = table->m_data+i;
}
void AddToHash(HashTable *table, void *item);
void *GetFromHash(HashTable *table, void *item);
....
void *ClearHash(HashTable *table);
In these functions you need to implement the logic of the hash table. While working they will be calling user defined callbacks to find out the index of the slot and if items are identical or not.
The users of this table should define their own structures and callback functions for every pair of types that they want to use:
struct HashItemK1V1
{
HashItemCore m_core;
K1 key;
V1 value;
};
int CalcHashK1V1(void *p)
{
HashItemK1V1 *param = (HashItemK1V1*)p;
// App code.
}
bool CompareK1V1(void *p1, void *p2)
{
HashItemK1V1 *param1 = (HashItemK1V1*)p1;
HashItemK1V1 *param2 = (HashItemK1V1*)p2;
// App code.
}
void FreeK1V1(void *p)
{
HashItemK1V1 *param = (HashItemK1V1*)p;
// App code if needed.
free(p);
}
This approach will not provide type safety because items will be passed around as void pointers assuming that every application structure starts with HashItemCore member. This will be sort of hand made polymorphysm. This is maybe not perfect, but this will work.
I implemented this approach in C++ using templates. But if you will strip out all fancies of C++, in the nutshell it will be exactly what I described above. I used my table in multiple projects and it worked like charm.
A generic hashtable in C is a bad idea.
a neat implementation will require function pointers, which are slow, since these functions cannot be inlined (the general case will need at least two function calls per hop: one to compute the hash value and one for the final compare)
to allow inlining of functions you'll either have to
write the code manually
or use a code generator
or macros. Which can get messy
IIRC, the linux kernel uses macros to create and maintain (some of?) its hashtables.
C does not have generic data types, so what you want to do (no extra allocations and no void* casting) is not really possible. You can use macros to generate the right data functions/structs on the fly, but you're trying to avoid macros as well.
So you need to give up at least one of your ideas.
You could have a generic data structure without extra allocations by allocating something like:
size_t key_len;
size_t val_len;
char key[];
char val[];
in one go and then handing out either void pointers, or adding an api for each specific type.
Alternatively, if you have a limited number of types you need to handle, you could also tag the value with the right one so now each entry contains:
size_t key_len;
size_t val_len;
int val_type;
char key[];
char val[];
but in the API at least you can verify that the requested type is the right one.
Otherwise, to make everything generic, you're left with either macros, or changing the language.

C find which pointer called function

Scenario:
There are multiple C structs, each of which contains a function pointer to the same function. These pointers can be different if necessary (pointers to pointers, etc.), but must all point, eventually, to the same function.
Problem:
When the function is called from one of the pointers, I need to retrieve, within the function, which struct it was called from.
e.g.
typedef struct A {
void * (*func)();
... /* Custom properties */
} * A;
typedef struct B {
void * (*func)();
... /* Custom properties */
} * B;
A a_init() {
A a;
... /* Custom initialisation, allocation, etc. */
a->func = myFunc;
return a;
}
B b_init() {
B b;
... /* Custom initialisation, allocation, etc. */
b->func = myFunc;
return b;
}
int main () {
A a = a_init();
void *something = a->func();
}
void * myFunc () {
// Need to get pointer to the instance of the struct this was called from here
}
Is there any way I can retrieve a pointer to the caller within myFunc? If necessary, I was thinking of creating pointers to pointers, etc. to the function, so each instance of an object would have a different pointer, and store all of them in a central location to match them up, but that obviously won't work if I can't even find the instance of the object or the pointer which was used. Any ideas?
Edit:
The question was intended a bit more broadly than I seem to have put it. Currying would be a great solution, if anyone has any ideas as to how to implement it in C. I had some ideas, but I just ended up coming right back to this spot with it.
I don't think there is any way within the language to do that, without explicitly passing some identifier (as an argument or a global) to myFunc. The address of a_init() exists somwhere within the call stack, but it's not accessible from the program.
It's like if somebody showed up at your door unannounced, how would you find out where that person came from without asking?
You can't do that. What you may do, however, is define your structs like this:
typedef struct A {
/* ... */
void *(*func)(void *);
} A;
typedef struct B {
/* ... */
void *(*func)(void *);
} B;
And your function like this:
void *myFunc(void *the_struct) {
/* ... */
}
And call like this:
A a = a_init();
void *something = a->func(a);
Alternatively, if you don't care about portability and for some reason need to be able to call it like a->func(), you may be able to create thunks/trampolines that add in the argument.
Can't be done.
In C++ when you call member functions the compiler implicitly adds this as the first function argument. Mimicking obj->method() syntax in C won't work because there's no implicit this.
This doesn't mean that OO is impossible in C, simply that you can't use the same syntax as C++ or Java do to it. It can still be done, but you have to be explicit:
void * myFunc (void *this) {
...
}
a->func(a);
b->func(b);

Polymorphism in C

I'm designing a program in C that manipulates geometric figures and it would be very convenient if every type of figure could be manipulated by the same primitives.
How can I do this in C?
You generally do it with function pointers. In other words, simple structures that hold both the data and pointers to functions which manipulate that data. We were doing that sort of stuff years before Bjarne S came onto the scene.
So, for example, in a communications class, you would have an open, read, write and close call which would be maintained as four function pointers in the structure, alongside the data for an object, something like:
typedef struct {
int (*open)(void *self, char *fspec);
int (*close)(void *self);
int (*read)(void *self, void *buff, size_t max_sz, size_t *p_act_sz);
int (*write)(void *self, void *buff, size_t max_sz, size_t *p_act_sz);
// And the data for the object goes here.
} tCommsClass;
tCommsClass commRs232;
commRs232.open = &rs232Open;
: :
commRs232.write = &rs232Write;
tCommsClass commTcp;
commTcp.open = &tcpOpen;
: :
commTcp.write = &tcpWrite;
The initialisation of those function pointers would actually be in a "constructor" such as rs232Init(tCommClass*), which would be responsible for setting up the default state of that particular object to match a specific class.
When you 'inherit' from that class, you just change the pointers to point to your own functions. Everyone that called those functions would do it through the function pointers, giving you your polymorphism:
int stat = (commTcp.open)(commTcp, "bigiron.box.com:5000");
Sort of like a manually configured vtable, in C++ parlance.
You could even have virtual classes by setting the pointers to NULL -the behaviour would be slightly different to C++ inasmuch as you would probably get a core dump at run-time rather than an error at compile time.
Here's a piece of sample code that demonstrates it:
#include <stdio.h>
// The top-level class.
typedef struct _tCommClass {
int (*open)(struct _tCommClass *self, char *fspec);
} tCommClass;
// Function for the TCP class.
static int tcpOpen (tCommClass *tcp, char *fspec) {
printf ("Opening TCP: %s\n", fspec);
return 0;
}
static int tcpInit (tCommClass *tcp) {
tcp->open = &tcpOpen;
return 0;
}
// Function for the HTML class.
static int htmlOpen (tCommClass *html, char *fspec) {
printf ("Opening HTML: %s\n", fspec);
return 0;
}
static int htmlInit (tCommClass *html) {
html->open = &htmlOpen;
return 0;
}
// Test program.
int main (void) {
int status;
tCommClass commTcp, commHtml;
// Same base class but initialized to different sub-classes.
tcpInit (&commTcp);
htmlInit (&commHtml);
// Called in exactly the same manner.
status = (commTcp.open)(&commTcp, "bigiron.box.com:5000");
status = (commHtml.open)(&commHtml, "http://www.microsoft.com");
return 0;
}
This produces the output:
Opening TCP: bigiron.box.com:5000
Opening HTML: http://www.microsoft.com
so you can see that the different functions are being called, depending on the sub-class.
I'm astonished, does no one have mentioned glib, gtk and the GObject system.
So instead of baking yet-another-oo-layer-upon-C. Why not use something that has proofed to work?
Regards
Friedrich
People have done silly things with various types of structs and relying on predictable padding - for example you can define a struct with a particular subset of another struct and it'll usually work. See below (code stolen from Wikipedia):
struct ifoo_version_42 {
long x, y, z;
char *name;
long a, b, c;
};
struct ifoo_old_stub {
long x, y;
};
void operate_on_ifoo(struct ifoo_version_42 *);
struct ifoo_old_stub s;
...
operate_on_ifoo(&s);
In this example, the ifoo_old_stub could be considered a superclass. As you can probably figure out, this relies on the fact that the same compiler will pad the two structs equivalently, and trying to access the x and y of a version-42 will work even if you pass a stub. This ought to work in the reverse as well. But AFAIK it doesn't necessarily work across compilers, so be careful if you want to send a struct of this format over the network, or save it in a file, or call a library function with one.
There's a reason polymorphism in C++ is pretty complicated to implement... (vtables, etc)

How do I implement callback functions in C?

gcc 4.4.3 c89
I am creating a client server application and I will need to implement some callback functions.
However, I am not too experienced in callbacks. And I am wondering if anyone knowns some good reference material to follow when designing callbacks. Is there any design patterns that are used for c. I did look at some patterns but there where all c++.
Many thanks for any suggestions,
Here is a very rough example. Please note, the only thing I'm trying to demonstrate is the use of callbacks, its designed to be informational, not a demonstration.
Lets say that we have a library (or any set of functions that revolve around a structure), we're going to have code that looks similar to this (of course, I'm naming it foo):
typedef struct foo {
int value;
char *text;
} foo_t;
That's simple enough. We'd then (conventionally) provide some means of allocating and freeing it, such as:
foo_t *foo_start(void)
{
foo_t *ret = NULL;
ret = (foo_t *)malloc(sizeof(struct foo));
if (ret == NULL)
return NULL;
return ret;
}
And then:
void foo_stop(foo_t *f)
{
if (f != NULL)
free(f);
}
But we want a callback, so we can define a function that will be entered when foo->text has something to report. To do that, we use a typed function pointer:
typedef void (* foo_callback_t)(int level, const char *data);
We also want any of the foo family of functions to be able to enter this callback conveniently. To do that, we need to add it to the structure, which would now look like this:
typedef struct foo {
int value;
char *text;
foo_callback_t callback;
} foo_t;
Then we write the function that will actually be entered (using the same prototype of our callback type):
void my_foo_callback(int val, char *data)
{
printf("Val is %d, data is %s\n", val, data == NULL ? "NULL" : data);
}
We then need to write some convenient way to say what function it actually points to:
void foo_reg_callback(foo_t *f, void *cbfunc)
{
f->callback = cbfunc;
}
And then our other foo functions can use it, for instance:
int foo_bar(foo_t *f, char *data)
{
if (data == NULL)
f->callback(LOG_ERROR, "data was NULL");
}
Note that in the above:
f->callback(LOG_ERROR, "data was NULL");
Is just like doing this:
my_foo_callback(LOG_ERROR, "data was NULL"):
Except that, we enter my_foo_callback() via a function pointer that we previously set, thereby giving us the flexibility to define our own handler on the fly (and even switch handlers if / as needed).
One of the biggest problems with callbacks (and even the code above) is type safety when using them. A lot of callbacks will take a void * pointer, usually named something like context which could be any type of data/memory. This provides great flexibility, but can be problematic if your pointers get away from you. For instance, you don't want to accidentally cast what is actually a struct * as char * (or int for that matter) by assignment. You can pass much more than simple strings and integers - structures, unions, enums, etc can all be passed. CCAN's type safe callbacks help you to avoid unwittingly evil casts (to / from void *) when doing so.
Again, this is an over simplified example that's designed to give you an overview of one possible way to use callbacks. Please consider it psuedo code that is meant only as an example.
IN C, callbacks are done with function pointers.
One feature that you definitely want is user defined context. Your code takes a void * pointer and makes it available to the callback function:
void callback(..., void *ctx);
void call_service_which_invokes_callback(...,
void (*cb)(..., void *ctx),
void *ctx);
This way, the callback can access any necessary state without having to use global variables.
Callbacks in C are implemented using function pointers. This might be helpful for starting points:
What is a "callback" in C and how are they implemented?
Also,
http://www.newty.de/fpt/callback.html#howto

OOP in C, implementation and a bug

I am trying to explore OOP in C. I am however a C n00b and would like to pick the brilliant brains of stackoverflow :)
My code is below:
#include <stdio.h>
#include <stdlib.h>
typedef struct speaker {
void (*say)(char *msg);
} speaker;
void say(char *dest) {
printf("%s",dest);
}
speaker* NewSpeaker() {
speaker *s;
s->say = say;
return s;
}
int main() {
speaker *s = NewSpeaker();
s->say("works");
}
However I'm getting a segfault from this, if I however remove all args from say and make it void, I can get it to work properly. What is wrong with my current code?
Also. While this implements a form of object in C, I'm trying to further implement it with inheritance, and even overriding/overloading of methods. How do you think I can implement such?
Thank You!
In your code, NewSpeaker() doesn't actually create a "new" speaker. You need to use a memory allocation function such as malloc or calloc.
speaker* NewSpeaker() {
speaker *s = malloc(sizeof(speaker));
s->say = say;
return s;
}
Without assigning the value from, for example, the return value of malloc, s is initialized to junk on the stack, hence the segfault.
Firstly, as it has been noted already, you failed to allocate memory for your 'speaker' object in 'NewSpeaker'. Without the unnecessary clutter it would look as follows
speaker* NewSpeaker(void)
{
speaker *s = malloc(sizeof *s);
s->say = say;
return s;
}
Note, that there's no cast on the result of the malloc, no type name in the 'sizeof' argument and the function parameter list is declared as '(void)', not just '()'.
Secondly, if you want to be able to create non-dynamic objects of your 'speaker' type, you might want to provide an in-place initialization function first, and then proceed from there
speaker* InitSpeaker(speaker* s)
{
assert(s != NULL);
s->say = say;
return s;
}
speaker* NewSpeaker(void)
{
void *raw = malloc(sizeof(speaker));
return raw != NULL ? InitSpeaker(raw) : NULL;
}
Finally, if you really want to create something like virtual C++ methods, you need to supply each method with a 'this' parameter (to get access to other members of your object). So it should probably look something like
typedef struct speaker
{
void (*say)(struct speaker *this, char *msg);
} speaker;
void say(speaker *this, char *dest)
{
printf("%s",dest);
}
This, of course, will require you to pass the corresponding argument every time you call a "method", but there's no way around this.
Additionally, I hope you know that you need "method" pointers in your "class" for "virtual methods" only. Ordinary (non-virtual) methods don't need such pointers.
Finally, a "traditional" C++ class imlementation doesn't store virtual method pointers inside each instance of the class. Instead, they are placed in a separate table (VMT), pointer to which is added to each instance. This saves a lot of memory. And this, BTW, makes especially good sense when you implement inheritance.
You can implement inheritance by embedding the parent class structure in the top of the child class structure. That way you can safely cast from the child class to the parent class. Here's an article on implementing OO features in C. If you want an existing solution, or just want to learn more about ways of achieving OO, look at the GObject library.

Resources