Project

General

Profile

Object Oriented C programming style » History » Version 3

Andreas Steffen, 27.11.2008 22:23
some reformulations

1 1 Martin Willi
= Object Oriented C programming style =
2 3 Andreas Steffen
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.
3 1 Martin Willi
4 1 Martin Willi
== Concept ==
5 3 Andreas Steffen
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 [http://xinehq.de/index.php/hackersguide#AEN390 xine project].
6 3 Andreas Steffen
To get an idea of the whole concept we recommend to examine the code directly.
7 1 Martin Willi
8 1 Martin Willi
== Future directions ==
9 3 Andreas Steffen
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.
10 1 Martin Willi
With some clever defines in the interface definition, we can eliminate these casts. Here an example for ''traffic_selector_t'':
11 1 Martin Willi
{{{
12 1 Martin Willi
@@ -67,6 +67,10 @@
13 1 Martin Willi
  * and a range of ports. IPv6 is not fully supported yet.
14 1 Martin Willi
  */
15 1 Martin Willi
 struct traffic_selector_t {
16 1 Martin Willi
+
17 1 Martin Willi
+#ifdef TRAFFIC_SELECTOR_IMPL
18 1 Martin Willi
+#define traffic_selector_t TRAFFIC_SELECTOR_IMPL
19 1 Martin Willi
+#endif
20 1 Martin Willi
 	
21 1 Martin Willi
 	/**
22 1 Martin Willi
 	 * Compare two traffic selectors, and create a new one
23 1 Martin Willi
@@ -293,4 +297,5 @@
24 1 Martin Willi
  */
25 1 Martin Willi
 printf_hook_functions_t traffic_selector_get_printf_hooks();
26 1 Martin Willi
 
27 1 Martin Willi
+#undef traffic_selector_t
28 1 Martin Willi
 #endif /* TRAFFIC_SELECTOR_H_ @} */
29 1 Martin Willi
}}}
30 3 Andreas Steffen
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.
31 1 Martin Willi
32 1 Martin Willi
== Gedit Snippets ==
33 2 Martin Willi
Being a gedit user, I created [http://trac.strongswan.org/attachment/wiki/ObjectOrientedC/gedit-snippets-strongswan.tar.gz?format=raw some snippets] to create interfaces, methods (including implementations and pointer assignement) and class implementations.