
Help in initializing function pointers within structures
Quote:
>Hi.
>I have a pointer to a function within a structure and I want it
>initialized "automatically". For example,
This won't happen in C. If you absolutely need such a feature, use
some other language like C++. In C++, you could declare a constructor
for the structure which will be called whenever such a structure
is instantiated, and can initialize some or all of its fields.
Quote:
>/* The header file */
>#ifndef SOP_H
>#define SOP_H
>struct sop
>{
> int (*func)(struct sop *s, FILE *ifp);
> initialize_sop() {
> func = sop_func;
> }
>};
Sorry, this just isn't C. In C, function declarations or definitions
must not appear inside a structure or union.
You can initialize a structure using an initializer; however, all of
the initializer elements must be constant expressions. This isn't
a problem in your case because the address of a function is an
``address constant''. So you can do:
struct sop {
int (*func)(struct sop *s, FILE *ifp);
}
struct sop sop_instance = { sop_func };
provided that sop_func has been suitably declared.
In traditional UNIX kernels, there is a static declaration which initializers
a whole array of structures with function pointers, much like:
#include "foo.h" /* foo driver */
#include "bar.h" /* bar driver */
struct operations {
int (*open)(/* .. args .. */);
int (*close)(/* .. args .. */);
/* ... other operations ... */
} device_table[MAX_DEVICES] = {
{ foo_open, foo_close, /* ... */ },
{ bar_open, bar_close, /* ... */ },
}
Each structure points to the basic operations of a device driver. The ``device
major number'' of a UNIX device has traditionally just been its index within
this array. (Though these days, drivers are dynamically loaded). Since C
originated as a language for implementing UNIX, it is useful to look at it for
hints of how some of the ways the language was intended to be used.