Project

General

Profile

Object Oriented C programming style » History » Version 4

Andreas Steffen, 27.11.2008 22:23
some reformulations

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