Project

General

Profile

Object Oriented C programming style » History » Version 1

Martin Willi, 27.11.2008 10:47

1 1 Martin Willi
= Object Oriented C programming style =
2 1 Martin Willi
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.
3 1 Martin Willi
4 1 Martin Willi
== Concept ==
5 1 Martin Willi
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 [http://xinehq.de/index.php/hackersguide#AEN390 xine project].
6 1 Martin Willi
To get an idea of the hole concept, it's a good idea to jump into the code directly.
7 1 Martin Willi
8 1 Martin Willi
== Future directions ==
9 1 Martin Willi
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.
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 1 Martin Willi
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.
31 1 Martin Willi
32 1 Martin Willi
== Gedit Snippets ==
33 1 Martin Willi
Being a gedit user, I created some snippets to create interfaces, methods (including implementations and pointer assignement) and class implementations.