Albert a écrit :
So structures are useful to group variables, so you can to refer to a
collection as a single entity. Wouldn't it be useful to also have the
ability to collect variable and functions?
Ask K&R say, C programs consist of variables to store the input and
functions to manipulate them.
This would make C object-oriented - how cool would that be?
Are there any problems with adding the ability to have functions
encapsulated in structures?
You can do this by defining an interface. I do this by using the
following schema:
The object has a pointer to the interface, called "lpVtbl", and other
fields.
The interface is a set of function pointers that defines the methods
available for the object.
For instance:
1) I define a forward declaration to the object
typedef struct _ArrayList ArrayList;
2) I define the interface functions:
typedef struct {
// Returns the number of elements stored
int (*GetCount)(ArrayList &AL);
// Is this collection read only?
int (*IsReadOnly)(ArrayList &AL);
// Sets this collection read-only or unsets the read-only flag
int (*SetReadOnly)(ArrayList &AL,int flag);
///SNIP /// SNIP /// SNIP
// Pushes a string, using the collection as a stack
int (*Push)(ArrayList &AL,void *str);
} ArrayListInterface;
3) I define the object
struct _ArrayList {
ArrayListInterface *lpVtbl; // The table of functions
size_t count; /* number of elements in the array */
void **contents; /* The contents of the collection */
size_t capacity; /* allocated space in the contents vector */
unsigned int flags; // Read-only or other flags
size_t ElementSize; // Size of the elements stored in this array
};
The usage is now very simple: For instance to get the count of elements
in an array list I do:
ArrayList al;
/// snip initialization, etc
int count = al.lpVtbl->GetCount(&al);
The lcc-win32 compiler uses this feature extensiveley to define
arraylists and other data structures in C.
jacob