Can structures contain functions?
Function-structures are used to move from abstract, socioeconomic notions of intended behavior to representations tied closely to physical behavior. Reverse engineering provides a base of decomposed 'behavior-in-context', — a set of building blocks that leads directly to parts whose physical behavior can be predicted.
Member functions inside the structure: Structures in C cannot have member functions inside a structure but Structures in C++ can have member functions along with data members.
No, but they can contain function pointers.
If your intent is to do some form of polymorphism in C then yes, it can be done:
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 data goes here. } tCommClass;
The typedef
above was for a structure I created for a general purpose communications library. In order to initialise the variable, you would:
tCommClass *makeCommTcp (void) { tCommClass *comm = malloc (sizeof (tCommClass)); if (comm != NULL) { comm->open = &tcpOpen; comm->close = &tcpOpen; comm->read = &tcpOpen; comm->write = &tcpWrite; } return comm; } tCommClass *makeCommSna (void) { tCommClass *comm = malloc (sizeof (tCommClass)); if (comm != NULL) { comm->open = &snaOpen; comm->close = &snaOpen; comm->read = &snaOpen; comm->write = &snaWrite; } return comm; } tCommClass *commTcp = makeCommTcp(); tCommClass *commSna = makeCommSna();
Then, to call the functions, something like:
// Pass commTcp as first params so we have a self/this variable // for accessing other functions and data area of object. int stat = (commTcp->open)(commTcp, "bigiron.box.com:5000");
In this way, a single type could be used for TCP, SNA, RS232 or even carrier pidgeons, with exactly the same interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With