Object Oriented C programming style » History » Version 2

« Previous - Version 2/8 (diff) - Next » - Current version
Martin Willi, 27.11.2008 10:48

= Object Oriented C programming style =
For new code in strongSwan, we use a object oriented programming style. We can use some useful modern programming paradigms, but still use standard C compiler and toolset.

This object oriented design is achieved by using function pointers heavily. Interfaces of classes are defined as struct with function pointers, and an implementations extends the struct by including the Interface as first struct member. The idea is based on the coding style of the [ xine project].
To get an idea of the hole concept, it's a good idea to jump into the code directly. Future directions
While the general concept is usuful and practical, it has a major drawback: The type insafety in the function pointer assignements (constructor) may lead to incompatible assignements.
With some clever defines in the interface definition, we can eliminate these casts. Here an example for ''traffic_selector_t'': {{{
@ -67,6 +67,10 @ * and a range of ports. IPv6 is not fully supported yet.
struct traffic_selector_t {

#define traffic_selector_t TRAFFIC_SELECTOR_IMPL
#endif /** * Compare two traffic selectors, and create a new one
@ -293,4 +297,5 @
printf_hook_functions_t traffic_selector_get_printf_hooks();

+#undef traffic_selector_t
#endif /* TRAFFIC_SELECTOR_H_ @} */
The actual implementation can then define the ''TRAFFIC_SELECTOR_IMPL'' to it's implementation (''private_traffic_selector_t'') before including the header. This rewrites the traffic selector interface for an implementation in a way that function pointer casts are unneded.

Gedit Snippets
Being a gedit user, I created [ some snippets] to create interfaces, methods (including implementations and pointer assignement) and class implementations.