Project

General

Profile

Object Oriented C programming style » History » Version 5

Tobias Brunner, 05.05.2009 19:43
link corrected

1 4 Andreas Steffen
h1. Object Oriented C programming style
2 4 Andreas Steffen
3 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.
4 1 Martin Willi
5 4 Andreas Steffen
6 4 Andreas Steffen
h2. Concept
7 4 Andreas Steffen
8 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.
9 1 Martin Willi
To get an idea of the whole concept we recommend to examine the code directly.
10 1 Martin Willi
11 4 Andreas Steffen
12 4 Andreas Steffen
h2. Future directions
13 1 Martin Willi
14 5 Tobias Brunner
While the general concept is useful and practical, it has a major drawback: The type unsafety in the function pointer assignments (constructor) may lead to incompatible assignements.
15 4 Andreas Steffen
With some clever defines in the interface definition, we can eliminate these casts. Here an example for _traffic_selector_t_:
16 4 Andreas Steffen
<pre>
17 1 Martin Willi
@@ -67,6 +67,10 @@
18 4 Andreas Steffen
** and a range of ports. IPv6 is not fully supported yet.
19 1 Martin Willi
  */
20 1 Martin Willi
 struct traffic_selector_t {
21 1 Martin Willi
+
22 1 Martin Willi
+#ifdef TRAFFIC_SELECTOR_IMPL
23 1 Martin Willi
+#define traffic_selector_t TRAFFIC_SELECTOR_IMPL
24 1 Martin Willi
+#endif
25 1 Martin Willi
 	
26 1 Martin Willi
 	/**
27 1 Martin Willi
 	 * Compare two traffic selectors, and create a new one
28 1 Martin Willi
@@ -293,4 +297,5 @@
29 1 Martin Willi
  */
30 1 Martin Willi
 printf_hook_functions_t traffic_selector_get_printf_hooks();
31 1 Martin Willi
 
32 1 Martin Willi
+#undef traffic_selector_t
33 1 Martin Willi
 #endif /* TRAFFIC_SELECTOR_H_ @} */
34 4 Andreas Steffen
</pre>
35 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.
36 1 Martin Willi
37 4 Andreas Steffen
38 1 Martin Willi
h2. Gedit Snippets
39 4 Andreas Steffen
40 5 Tobias Brunner
Being a gedit user, I created some snippets (attachment:gedit-snippets-strongswan.tar.gz) to create interfaces, methods (including implementations and pointer assignement) and class implementations.