Object Oriented C programming style » History » Version 4

« Previous - Version 4/8 (diff) - Next » - Current version
Andreas Steffen, 27.11.2008 22:23
some reformulations

Object Oriented C programming style

For new code in strongSwan, we use an object oriented programming style. This allows us to employ modern programming paradigms, but still use the standard C compiler and toolset.


This object oriented design is achieved by heavy use of function pointers. Interfaces of classes are defined as a struct with function pointers, and an implementation extends the struct by including the Interface as its first struct member. The idea is based on the coding style of the xine project.
To get an idea of the whole concept we recommend to examine the code directly.

Future directions

While the general concept is useful and practical, it has a major drawback: The type insafety in the function pointer assignments (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

      * 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 not needed.

Gedit Snippets

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