Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What techniques/strategies do people use for building objects in C (not C++)?

I am especially interested in objects meant to be used from within C, as opposed to implementations of objects that form the core of interpreted languages such as python.

like image 369
Setjmp Avatar asked Aug 04 '09 05:08

Setjmp


1 Answers

I tend to do something like this:

struct foo_ops {
    void (*blah)(struct foo *, ...);
    void (*plugh)(struct foo *, ...);
};
struct foo {
    struct foo_ops *ops;
    /* data fields for foo go here */
};

With these structure definitions, the code implementing foo looks something like this:

static void plugh(struct foo *, ...) { ... }
static void blah(struct foo *, ...) { ... }

static struct foo_ops foo_ops = { blah, plugh };

struct foo *new_foo(...) {
   struct foo *foop = malloc(sizeof(*foop));
   foop->ops = &foo_ops;
   /* fill in rest of *foop */
   return foop;
} 

Then, in code that uses foo:

struct foo *foop = new_foo(...);
foop->ops->blah(foop, ...);
foop->ops->plugh(foop, ...);

This code can be tidied up with macros or inline functions so it looks more C-like

foo_blah(foop, ...);
foo_plugh(foop, ...);

although if you stick with a reasonably short name for the "ops" field, simply writing out the code shown originally isn't particularly verbose.

This technique is entirely adequate for implementing a relatively simple object-based designs in C, but it does not handle more advanced requirements such as explicitly representing classes, and method inheritance. For those, you might need something like GObject (as EFraim mentioned), but I'd suggest making sure you really need the extra features of the more complex frameworks.

like image 87
Dale Hagglund Avatar answered Sep 25 '22 08:09

Dale Hagglund