开发者

Functions in structure

Can st开发者_运维知识库ructures contain functions?


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.


edit Cleared up ambiguity with the use of 'data types'

Not in C. struct types can only contain data.

From Section 6.7.2.1 of the ISO C99 Standard.

A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.


No, you cannot. A structure cannot contain a declaration of a function but they can contain a definition of a function. A structure can only contain data types, pointers, pointers to different function. You can make a pointer to a function and then access from the structure.

#include<iostream>
#include<cstring>
using namespace std;

struct full_name
{
  char *fname;
  char *lname;
  void (*show)(char *,char*);
};

void show(char *a1,char * a2)
{
  cout<<a1<<"-"<<a2<<endl;
}

int main()
{  
  struct full_name loki;
  loki.fname="Mohit";
  loki.lname="Dabas";
  loki.show=show;
  loki.show(loki.fname,loki.lname);

  return 0;     
}


In C, structures are allowed to contain on data values and not the function pointers. Not allowed in C. but the following works literally fine when checked with gcc.

enter code here

#include <stdio.h>

struct st_func_ptr{
        int data;
        int (*callback) ();
};

int cb(){
        printf(" Inside the call back \n");
        return 0;
}

int main() {
        struct st_func_ptr sfp = {10, cb};

        printf("return value = %d \n",sfp.callback());

        printf(" Inside main\n");
        return 0;
}

So, am confused ...


It's all right. In the linux kernel code,you will find many structures contain functions. such as:

/*


* The type of device, "struct device" is embedded in. A class
 * or bus can contain devices of different types
 * like "partitions" and "disks", "mouse" and "event".
 * This identifies the device type and carries type-specific
 * information, equivalent to the kobj_type of a kobject.
 * If "name" is specified, the uevent will contain it in
 * the DEVTYPE variable.
 */
struct device_type {
        const char *name;
        struct attribute_group **groups;
        int (*uevent)(struct device *dev, struct kobj_uevent_env *env);
        void (*release)(struct device *dev);
        int (*suspend)(struct device * dev, pm_message_t state);
        int (*resume)(struct device * dev);
};


Yes its possible to declare a function and the function definition is not allowed and that should be the function pointer.

Its based on C99 tagged structure.

Lokesh V


They can, but there is no inherent advantage in usual C programming.

In C, all functions are in the global space anyway, so you get no information hiding by tucking them in a function. paxdiablo 's example is a way to organize functions into a struct, but you must see has to dereference each one anyway to use it.

The standard organizational structure of C is the File, with the interfaces in the header and the implementations in the source.

That is how libc is done and that is how almost all C libraries are done.

Moder C compilers allow you to define and implement functions in the same source file, and even implement static functions in header files. This unfortunately leads to some confusion as to what goes where, and you can get unusual solutions like cramming functions into structs, source-only programs with no headers, etc. You lose the advantage of separating interface from implementation that way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜