Genivia Home Documentation
README.md Source File

updated Tue Jul 4 2017 by Robert van Engelen
 
README.md
Go to the documentation of this file.
1 
2 C and C++ XML Data Bindings {#mainpage}
3 ===========================
4 
5 [TOC]
6 
7 Introduction {#intro}
8 ============
9 
10 This article gives a detailed overview of the gSOAP C and C++ XML data bindings
11 and highlights the advantages, concepts, usage, and implementation aspects of
12 XML data bindings.
13 
14 The major advantage of XML data bindings is that your application data is
15 always **type safe** in C and C++ by binding XML schema types to C/C++ types.
16 So integers in XML are bound to C integers, strings in XML are bound to C or
17 C++ strings, complex types in XML are bound to C structs or C++ classes, and so
18 on. The structured data you create and accept will fit the data model and is
19 **static type safe**. In other words, by leveraging strong typing in C/C++,
20 your XML data meets **XML schema validation requirements** and satisfies **XML
21 interoperability requirements**.
22 
23 The gSOAP data bindings are more powerful than simply representing C/C++ data
24 in XML. In fact, the tools implement **true serialization** of C/C++ data in
25 XML, including the serialization of cyclic graph structures. The gSOAP tools
26 also generate routines for deep copying and deep deletion of C/C++ data
27 structures to simplify memory management. In addition, C/C++ structures are
28 deserialized into managed memory, managed by the gSOAP `soap` context.
29 
30 At the end of this document two examples are given to illustrate the
31 application of XML data bindings. The first simple example `address.cpp` shows
32 how to use wsdl2h to bind an XML schema to C++. The C++ application reads and
33 writes an XML file into and from a C++ "address book" data structure. The C++
34 data structure is an STL vector of address objects. The second example
35 `graph.cpp` shows how C++ data can be accurately serialized as a tree, digraph,
36 and cyclic graph in XML. The digraph and cyclic graph serialization rules
37 implement SOAP 1.1/1.2 multi-ref encoding with id-ref attributes to link
38 elements through IDREF XML references, creating a an XML graph with pointers to
39 XML nodes that preserves the structural integrity of the serialized C++ data.
40 
41 These examples demonstrate XML data bindings only for relatively simple data
42 structures and types. The gSOAP tools support more than just these type of
43 structures to serialize in XML. There are practically no limits to
44 enable XML serialization of C and C++ types.
45 
46 Support for XML schema components is unlimited. The wsdl2h tool maps schemas
47 to C and C++ using built-in intuitive mapping rules, while allowing the
48 mappings to be customized using a `typemap.dat` file with mapping instructions
49 for wsdl2h.
50 
51 The information in this document is applicable to gSOAP 2.8.26 and later
52 versions that support C++11 features. However, C++11 is not required to use
53 this material and the examples included, unless we need smart pointers and
54 scoped enumerations. While most of the examples in this document are given in
55 C++, the concepts also apply to C with the exception of containers, smart
56 pointers, classes and their methods. None of these exceptions limit the use of
57 the gSOAP tools for C in any way.
58 
59 The data binding concepts described in this document were first envisioned in
60 1999 by Prof. Robert van Engelen at the Florida State University. An
61 implementation was created in 2000, named "stub/skeleton compiler". The first
62 articles on its successor version "gSOAP" appeared in 2002. The principle of
63 mapping XSD components to C/C++ types and vice versa is now widely adopted in
64 systems and programming languages, including Java web services and by C# WCF.
65 
66 We continue to be committed to our goal to empower C/C++ developers with
67 powerful autocoding tools for XML. Our commitment started in the very early
68 days of SOAP by actively participating in
69 [SOAP interoperability testing](http://www.whitemesa.com/interop.htm),
70 participating in the development and testing of the
71 [W3C XML Schema Patterns for Databinding Interoperability](http://www.w3.org/2002/ws/databinding),
72 and continues by contributing to the development of
73 [OASIS open standards](https://www.oasis-open.org) in partnership with leading
74 IT companies.
75 
76 🔝 [Back to table of contents](#)
77 
78 Mapping WSDL and XML schemas to C/C++ {#tocpp}
79 =====================================
80 
81 To convert WSDL and XML schemas (XSD files) to code, use the wsdl2h command to
82 generate the data binding interface code that is saved to a special gSOAP
83 header file with WSDL service declarations and the data binding interface:
84 
85  wsdl2h [options] -o file.h ... XSD and WSDL files ...
86 
87 This command converts WSDL and XSD files to C++ (or pure C with wsdl2h option
88 `-c`) and saves the data binding interface to a gSOAP header file `file.h` that
89 uses familiar C/C++ syntax extended with `//gsoap` [directives](#directives)
90 and annotations. Notational conventions are used in the data binding interface
91 to declare serializable C/C++ types and functions for Web service operations.
92 
93 The WSDL 1.1/2.0, SOAP 1.1/1.2, and XSD 1.0/1.1 standards are supported by the
94 gSOAP tools. In addition, the most popular WS specifications are also
95 supported, including WS-Addressing, WS-ReliableMessaging, WS-Discovery,
96 WS-Security, WS-Policy, WS-SecurityPolicy, and WS-SecureConversation.
97 
98 This document focusses on XML data bindings. XML data bindings for C/C++ bind
99 XML schema types to C/C++ types. So integers in XML are bound to C integers,
100 strings in XML are bound to C or C++ strings, complex types in XML are bound to
101 C structs or C++ classes, and so on.
102 
103 A data binding is dual. Either you start with WSDLs and/or XML schemas that
104 are mapped to equivalent C/C++ types, or you start with C/C++ types that are
105 mapped to XSD types. Either way, the end result is that you can serialize
106 C/C++ types in XML such that your XML is an instance of XML schema(s) and is
107 validated against these schema(s).
108 
109 This covers all of the following standard XSD components with their optional
110 attributes and properties:
111 
112 XSD component | attributes and properties
113 -------------- | -------------------------
114 schema | targetNamespace, version, elementFormDefault, attributeFormDefault, defaultAttributes
115 attribute | name, ref, type, use, default, fixed, form, targetNamespace, wsdl:arrayType
116 element | name, ref, type, default, fixed, form, nillable, abstract, substitutionGroup, minOccurs, maxOccurs, targetNamespace
117 simpleType | name
118 complexType | name, abstract, mixed, defaultAttributesApply
119 all | *n/a*
120 choice | minOccurs, maxOccurs
121 sequence | minOccurs, maxOccurs
122 group | name, ref, minOccurs, maxOccurs
123 attributeGroup | name, ref
124 any | minOccurs, maxOccurs
125 anyAttribute | *n/a*
126 
127 And also the following standard XSD directives are covered:
128 
129 directive | description
130 ---------- | -----------
131 import | Imports a schema into the importing schema for referencing
132 include | Include schema component definitions into a schema
133 override | Override by replacing schema component definitions
134 redefine | Extend or restrict schema component definitions
135 annotation | Annotates a component
136 
137 The XSD facets and their mappings to C/C++ are:
138 
139 XSD facet | maps to
140 -------------- | -------
141 enumeration | `enum`
142 simpleContent | class/struct wrapper with `__item` member
143 complexContent | class/struct
144 list | `enum*` bitmask (`enum*` enumerates up to 64 bit masks)
145 extension | class/struct inheritance/extension
146 restriction | `typedef` and class/struct inheritance/redeclaration
147 length | `typedef` with restricted content length annotation
148 minLength | `typedef` with restricted content length annotation
149 maxLength | `typedef` with restricted content length annotation
150 minInclusive | `typedef` with numerical value range restriction annotation
151 maxInclusive | `typedef` with numerical value range restriction annotation
152 minExclusive | `typedef` with numerical value range restriction annotation
153 maxExclusive | `typedef` with numerical value range restriction annotation
154 precision | `typedef` with pattern annotation (pattern used for output, but input is not validated)
155 scale | `typedef` with pattern annotation (pattern used for output, but input is not validated)
156 totalDigits | `typedef` with pattern annotation (pattern used for output, but input is not validated)
157 fractionDigits | `typedef` with pattern annotation (pattern used for output, but input is not validated)
158 pattern | `typedef` with pattern annotation (define `soap::fsvalidate` callback to validate patterns)
159 union | string with union of value
160 
161 All primitive XSD types are supported, including but not limited to the
162 following XSD types:
163 
164 XSD type | maps to
165 ---------------- | -------
166 any/anyType | `_XML` string with literal XML content (or enable DOM with wsdl2h option `-d`)
167 anyURI | string (i.e. `char*`, `wchar_t*`, `std::string`, `std::wstring`)
168 string | string (i.e. `char*`, `wchar_t*`, `std::string`, `std::wstring`)
169 boolean | `bool` (C++) or `enum xsd__boolean` (C)
170 byte | `char` (i.e. `int8_t`)
171 short | `short` (i.e. `int16_t`)
172 int | `int` (i.e. `int32_t`)
173 long | `LONG64` (i.e. `long long` and `int64_t`)
174 unsignedByte | `unsigned char` (i.e. `uint8_t`)
175 unsignedShort | `unsigned short` (i.e. `uint16_t`)
176 unsignedInt | `unsigned int` (i.e. `uint32_t`)
177 unsignedLong | `ULONG64` (i.e. `unsigned long long` and `uint64_t`)
178 float | `float`
179 double | `double`
180 integer | string or `#import "custom/int128.h"` to use 128 bit `xsd__integer`
181 decimal | string or `#import "custom/long_double.h"` to use `long double`
182 precisionDecimal | string
183 duration | string or `#import "custom/duration.h"` to use 64 bit `xsd__duration`
184 dateTime | `time_t` or `#import "custom/struct_tm.h"` to use `struct tm` for `xsd__dateTime`
185 time | string or `#import "custom/long_time.h"` to use 64 bit `xsd__time`
186 date | string or `#import "custom/struct_tm_date.h"` to use `struct tm` for `xsd__date`
187 hexBinary | special class/struct `xsd__hexBinary`
188 base64Bianry | special class/struct `xsd__base64Binary`
189 QName | `_QName` string (URI normalization rules are applied)
190 
191 All other primitive XSD types not listed above are mapped to strings, by
192 wsdl2h generating a typedef to string for these types. For example,
193 `xsd:token` is bound to a C++ or C string:
194 
195 ```cpp
196 typedef std::string xsd__token; // C++
197 typedef char *xsd__token; // C (wsdl2h option -c)
198 ```
199 
200 This associates a compatible value space to the type with the appropriate XSD
201 type name used by the soapcpp2-generated serializers.
202 
203 It is possible to remap types by adding the appropriate mapping rules to
204 `typemap.dat` as we will explain in more detail in the next section.
205 
206 Imported custom serializers are intended to extend the C/C++ type bindings when
207 the default binding to string is not satisfactory to your taste and if the
208 target platform supports these C/C++ types. To add custom serializers to
209 `typemap.dat` for wsdl2h, see [adding custom serializers](#custom) below.
210 
211 🔝 [Back to table of contents](#)
212 
213 Using typemap.dat to customize data bindings {#typemap}
214 ============================================
215 
216 Use a `typemap.dat` file to redefine namespace prefixes and to customize type
217 bindings for the the generated header files produced by the wsdl2h tool. The
218 `typemap.dat` is the default file processed by wsdl2h. Use wsdl2h option `-t`
219 to specify a different file.
220 
221 Declarations in `typemap.dat` can be broken up over multiple lines by
222 continuing on the next line by ending each line to be continued with a
223 backslash `\`. The limit is 4095 characters per line, whether the line is
224 broken up or not.
225 
226 🔝 [Back to table of contents](#)
227 
228 XML namespace bindings {#typemap1}
229 ----------------------
230 
231 The wsdl2h tool generates C/C++ type declarations that use `ns1`, `ns2`, etc.
232 as schema-binding URI prefixes. These default prefixes are generated somewhat
233 arbitrarily for each schema targetNamespace URI, meaning that their ordering
234 may change depending on the WSDL and XSD order of processing with wsdl2h.
235 
236 Therefore, it is **strongly recommended** to declare your own prefix for each
237 schema URI in `typemap.dat` to reduce maintaince effort of your code. This
238 is more robust when anticipating possible changes of the schema(s) and/or the
239 binding URI(s) and/or the tooling algorithms.
240 
241 The first and foremost important thing to do is to define prefix-URI bindings
242 for our C/C++ code by adding the following line(s) to our `typemap.dat` or make
243 a copy of this file and add the line(s) that bind our choice of prefix name to
244 each URI:
245 
246  prefix = "URI"
247 
248 For example, to use `g` as a prefix for the "urn:graph" XML namespace:
249 
250  g = "urn:graph"
251 
252 This produces `g__name` C/C++ type names that are bound to the "urn:graph"
253 schema by association of `g` to the generated C/C++ types.
254 
255 This means that `<g:name xmlns:g="urn:graph">` is parsed as an instance of a
256 `g__name` C/C++ type. Also `<x:name xmlns:x="urn:graph">` parses as an
257 instance of `g__name`, because the prefix `x` has the same URI value
258 `urn:graph`. Prefixes in XML have local scopes (like variables in a block).
259 
260 The first run of wsdl2h will reveal the XML namespace URIs, so you do not need
261 to search WSDLs and XSD files for all of the target namespaces. Just copy them
262 from the generated header file after the first run into `typemap.dat` for
263 editing.
264 
265 @note Only define a namespace prefix once in `typemap.dat`. That is, do not
266 use the same prefix for multiple XML namespace URIs. This is to avoid
267 namespace conflicts that may cause failed builds and failures in XML parsing
268 and XML schema validation.
269 
270 🔝 [Back to table of contents](#)
271 
272 XSD type bindings {#typemap2}
273 -----------------
274 
275 Custom C/C++ type bindings can be declared in `typemap.dat` to associate C/C++
276 types with specific schema types. These type bindings have four parts:
277 
278  prefix__type = declaration | use | ptruse
279 
280 where
281 
282 - `prefix__type` is the schema type to be customized (the `prefix__type` name
283  uses the common double underscore naming convention);
284 - `declaration` declares the C/C++ type in the wsdl2h-generated header file.
285  This part can be empty if no explicit declaration is needed;
286 - `use` is an optional part that specifies how the C/C++ type is used in the
287  code. When omitted, it is the same as `prefix__type`;
288 - `ptruse` is an optional part that specifies how the type is used as a pointer
289  type. By default it is the `use` type name with a `*` or C++11
290  `std::shared_ptr<>` when enabled (see further below). If `use` is already a
291  pointer type by the presence of a `*` in the `use` part, then the default
292  `ptruse` type is the same as the `use` type (that is, no double pointer `**`
293  will be created in this case).
294 
295 For example, to map `xsd:duration` to a `long long` (`LONG64`) type that holds
296 millisecond duration values, we can use the custom serializer declared in
297 `custom/duration.h` by adding the following line to `typemap.dat`:
298 
299  xsd__duration = #import "custom/duration.h"
300 
301 Here, we omitted the second and third parts, because `xsd__duration` is the
302 name that wsdl2h uses for this type in our generated code so we should leave
303 the `use` part unspecified. The third part is omitted to let wsdl2h use
304 `xsd__duration *` for pointers or `std::shared_ptr<xsd__duration>` if smart
305 pointers are enabled.
306 
307 To map `xsd:string` to `wchar_t*` wide strings:
308 
309  xsd__string = | wchar_t* | wchar_t*
310 
311 Note that the first part is empty, because `wchar_t` is a C type and does not
312 need to be declared. A `ptruse` part is also defined in this example, but does
313 not need to be because the `use` part `wchar_t*` is already a pointer.
314 
315 When the auto-generated declaration should be preserved but the `use` or
316 `ptruse` parts replaced, then we use an ellipsis for the declaration part:
317 
318  prefix__type = ... | use | ptruse
319 
320 This is useful to map schema polymorphic types to C types for example, where we
321 need to be able to both handle a base type and its extensions as per schema
322 extensibility. Say we have a base type called ns:base that is extended, then we
323 can remap this to a C type that permits referening the extended types via a
324 `void*` as follows:
325 
326  ns__base = ... | int __type_base; void*
327 
328 such that `__type_base` and `void*` will be used to (de)serialize any data
329 type, including base and its derived types. The `__type_base` integer is set
330 to a `SOAP_TYPE_T` value to indicate what type of data the `void*` pointer
331 points to.
332 
333 🔝 [Back to table of contents](#)
334 
335 Custom serializers for XSD types {#custom}
336 --------------------------------
337 
338 In the previous part we saw how a custom serializer is used to bind
339 `xsd:duration` to a `long long` (`LONG64` or `int64_t`) type to store millisecond
340 duration values:
341 
342  xsd__duration = #import "custom/duration.h"
343 
344 The `xsd__duration` type is an alias of `long long` (`LONG64` or `int64_t`).
345 
346 While wsdl2h will use this binding declared in `typemap.dat` automatically, you
347 will also need to compile `custom/duration.c`. Each custom serializer has a
348 header file and an implementation file written in C. You can compile these in
349 C++ (rename files to `.cpp` if needed).
350 
351 We will discuss the custom serializers that are available to you.
352 
353 🔝 [Back to table of contents](#)
354 
355 ### xsd:integer {#custom-1}
356 
357 The wsdl2h tool maps `xsd:integer` to a string by default. To map `xsd:integer` to
358 the 128 bit big int type `__int128_t`:
359 
360  xsd__integer = #import "custom/int128.h"
361 
362 The `xsd__integer` type is an alias of `__int128_t`.
363 
364 @warning Beware that the `xsd:integer` value space of integers is in principle
365 unbounded and values can be of arbitrary length. A value range fault
366 `SOAP_TYPE` (value exceeds native representation) or `SOAP_LENGTH` (value
367 exceeds range bounds) will be thrown by the deserializer if the value is out of
368 range.
369 
370 Other XSD integer types that are restrictions of `xsd:integer`, are
371 `xsd:nonNegativeInteger` and `xsd:nonPositiveInteger`, which are further restricted
372 by `xsd:positiveInteger` and `xsd:negativeInteger`. To bind these types to
373 `__int128_t` add the following definitions to `typemap.dat`:
374 
375  xsd__nonNegativeInteger = typedef xsd__integer xsd__nonNegativeInteger 0 : ;
376  xsd__nonPositiveInteger = typedef xsd__integer xsd__nonPositiveInteger : 0 ;
377  xsd__positiveInteger = typedef xsd__integer xsd__positiveInteger 1 : ;
378  xsd__negativeInteger = typedef xsd__integer xsd__negativeInteger : -1 ;
379 
380 Or simply uncomment these definitions in `typemap.dat` when you are using the
381 latest gSOAP releases.
382 
383 @note If `__int128_t` 128 bit integers are not supported on your platform and if it
384 is certain that `xsd:integer` values are within 64 bit value bounds for your
385 application's use, then you can map this type to `LONG64`:
386 
387  xsd__integer = typedef LONG64 xsd__integer;
388 
389 @note Again, a value range fault `SOAP_TYPE` or `SOAP_LENGTH` will be thrown by
390 the deserializer if the value is out of range.
391 
392 After running wsdl2h and soapcpp2, compile `custom/int128.c` with your project.
393 
394 @see Section [numerical types](#toxsd5).
395 
396 🔝 [Back to table of contents](#)
397 
398 ### xsd:decimal {#custom-2}
399 
400 The wsdl2h tool maps `xsd:decimal` to a string by default. To map `xsd:decimal` to
401 extended precision floating point:
402 
403  xsd__decimal = #import "custom/long_double.h" | long double
404 
405 By contrast to all other custom serializers, this serializer enables `long
406 double` natively without requiring a new binding name (`xsd__decimal` is NOT
407 defined).
408 
409 If your system supports `<quadmath.h>` quadruple precision floating point
410 `__float128`, you can map `xsd:decimal` to `xsd__decimal` that is an alias of
411 `__float128`:
412 
413  xsd__decimal = #import "custom/float128.h"
414 
415 @warning Beware that `xsd:decimal` is in principle a decimal value with arbitraty
416 lengths. A value range fault `SOAP_TYPE` will be thrown by the deserializer if
417 the value is out of range.
418 
419 In the XML payload the special values `INF`, `-INF`, `NaN` represent plus or
420 minus infinity and not-a-number, respectively.
421 
422 After running wsdl2h and soapcpp2, compile `custom/long_double.c` with your
423 project.
424 
425 @see Section [numerical types](#toxsd5).
426 
427 🔝 [Back to table of contents](#)
428 
429 ### xsd:dateTime {#custom-3}
430 
431 The wsdl2h tool maps `xsd:dateTime` to `time_t` by default.
432 
433 The trouble with `time_t` when represented as 32 bit `long` integers is that it
434 is limited to dates between 1970 and 2038. A 64 bit `time_t` is safe to use if
435 the target platform supports it, but lack of 64 bit `time_t` portability may
436 still cause date range issues.
437 
438 For this reason `struct tm` should be used to represent wider date ranges. This
439 custom serializer avoids using date and time information in `time_t`. You get
440 the raw date and time information. You only lose the day of the week
441 information. It is always Sunday (`tm_wday=0`).
442 
443 To map `xsd:dateTime` to `xsd__dateTime` which is an alias of `struct tm`:
444 
445  xsd__dateTime = #import "custom/struct_tm.h"
446 
447 If the limited date range of `time_t` is not a problem but you want to increase
448 the time precision with fractional seconds, then we suggest to map `xsd:dateTime`
449 to `struct timeval`:
450 
451  xsd__dateTime = #import "custom/struct_timeval.h"
452 
453 If the limited date range of `time_t` is not a problem but you want to use the
454 C++11 time point type `std::chrono::system_clock::time_point` (which internally
455 uses `time_t`):
456 
457  xsd__dateTime = #import "custom/chrono_time_point.h"
458 
459 Again, we should make sure that the dates will not exceed the date range when
460 using the default `time_t` binding for `xsd:dateTime` or when binding
461 `xsd:dateTime` to `struct timeval` or to `std::chrono::system_clock::time_point`.
462 These are safe to use in applications that use `xsd:dateTime` to record date
463 stamps within a given window. Otherwise, we recommend the `struct tm` custom
464 serializer.
465 
466 After running wsdl2h and soapcpp2, compile `custom/struct_tm.c` with your
467 project.
468 
469 You could even map `xsd:dateTime` to a plain string (use `char*` with C and
470 `std::string` with C++). For example:
471 
472  xsd__dateTime = | char*
473 
474 @see Section [date and time types](#toxsd7).
475 
476 🔝 [Back to table of contents](#)
477 
478 ### xsd:date {#custom-4}
479 
480 The wsdl2h tool maps `xsd:date` to a string by default. We can map `xsd:date` to
481 `struct tm`:
482 
483  xsd__date = #import "custom/struct_tm_date.h"
484 
485 The `xsd__date` type is an alias of `struct tm`. The serializer ignores the
486 time part and the deserializer only populates the date part of the struct,
487 setting the time to 00:00:00. There is no unreasonable limit on the date range
488 because the year field is stored as an integer (`int`).
489 
490 After running wsdl2h and soapcpp2, compile `custom/struct_tm_date.c` with your
491 project.
492 
493 @see Section [date and time types](#toxsd7).
494 
495 🔝 [Back to table of contents](#)
496 
497 ### xsd:time {#custom-5}
498 
499 The wsdl2h tool maps `xsd:time` to a string by default. We can map `xsd:time` to
500 an `unsigned long long` (`ULONG64` or `uint64_t`) integer with microsecond time
501 precision:
502 
503  xsd__time = #import "custom/long_time.h"
504 
505 This type represents 00:00:00.000000 to 23:59:59.999999, from `0` to an upper
506 bound of `86399999999`. A microsecond resolution means that a 1 second
507 increment requires an increment of 1000000 in the integer value. The serializer
508 adds a UTC time zone.
509 
510 After running wsdl2h and soapcpp2, compile `custom/long_time.c` with your
511 project.
512 
513 @see Section [date and time types](#toxsd7).
514 
515 🔝 [Back to table of contents](#)
516 
517 ### xsd:duration {#custom-6}
518 
519 The wsdl2h tool maps `xsd:duration` to a string by default, unless `xsd:duration`
520 is mapped to a `long long` (`LONG64` or `int64_t`) type with with millisecond
521 (ms) time duration precision:
522 
523  xsd__duration = #import "custom/duration.h"
524 
525 The `xsd__duration` type is a 64 bit signed integer that can represent
526 106,751,991,167 days forwards (positive) and backwards (negative) in time in
527 increments of 1 ms (1/1000 of a second).
528 
529 Rescaling of the duration value by may be needed when adding the duration value
530 to a `time_t` value, because `time_t` may or may not have a seconds resolution,
531 depending on the platform and possible changes to `time_t`.
532 
533 Rescaling is done automatically when you add a C++11 `std::chrono::nanoseconds`
534 value to a `std::chrono::system_clock::time_point` value. To use
535 `std::chrono::nanoseconds` as `xsd:duration`:
536 
537  xsd__duration = #import "custom/chrono_duration.h"
538 
539 This type can represent 384,307,168 days (2^63 nanoseconds) forwards and
540 backwards in time in increments of 1 ns (1/1,000,000,000 of a second).
541 
542 Certain observations with respect to receiving durations in years and months
543 apply to both of these serializer decoders for `xsd:duration`.
544 
545 After running wsdl2h and soapcpp2, compile `custom/duration.c` with your
546 project.
547 
548 @see Section [time duration types](#toxsd8).
549 
550 🔝 [Back to table of contents](#)
551 
552 Custom Qt serializers for XSD types {#qt}
553 -----------------------------------
554 
555 The gSOAP distribution includes several custom serializers for Qt types. Also
556 Qt container classes are supported, see
557 [the built-in typemap.dat variables $CONTAINER and $POINTER](#typemap5).
558 
559 This feature requires gSOAP 2.8.34 or higher and Qt 4.8 or higher.
560 
561 Each Qt custom serializer has an interface header file for soapcpp2 and a C++
562 implementation file to be compiled with your project.
563 
564 Other Qt primitive types that are Qt typedefs of C/C++ types do not require a
565 custom serializer.
566 
567 🔝 [Back to table of contents](#)
568 
569 ### xsd:string {#qt-1}
570 
571 To use Qt strings instead of C++ strings, add the following definition to
572 `typemap.dat`:
573 
574  xsd__string = #import "custom/qstring.h"
575 
576 After running wsdl2h and soapcpp2, compile `custom/qstring.cpp` with your
577 project.
578 
579 🔝 [Back to table of contents](#)
580 
581 ### xsd:base64Binary {#qt-2}
582 
583 To use Qt byte arrays for `xsd:base64Binary` instead of the
584 `xsd__base64Binary` class, add the following definition to `typemap.dat`:
585 
586  xsd__base64Binary = #import "custom/qbytearray_base64.h"
587 
588 After running wsdl2h and soapcpp2, compile `custom/qbytearray_base64.cpp` with
589 your project.
590 
591 🔝 [Back to table of contents](#)
592 
593 ### xsd:hexBinary {#qt-3}
594 
595 To use Qt byte arrays for `xsd:hexBinary` instead of the `xsd__base64Binary`
596 class, add the following definition to `typemap.dat`:
597 
598  xsd__hexBinary = #import "custom/qbytearray_hex.h"
599 
600 After running wsdl2h and soapcpp2, compile `custom/qbytearray_hex.cpp` with
601 your project.
602 
603 🔝 [Back to table of contents](#)
604 
605 ### xsd:dateTime {#qt-4}
606 
607 To use Qt QDateTime for `xsd:dateTime`, add the following definition to
608 `typemap.dat`:
609 
610  xsd__dateTime = #import "custom/datetime.h"
611 
612 After running wsdl2h and soapcpp2, compile `custom/qdatetime.cpp` with
613 your project.
614 
615 🔝 [Back to table of contents](#)
616 
617 ### xsd:date {#qt-5}
618 
619 To use Qt QDate for `xsd:date`, add the following definition to
620 `typemap.dat`:
621 
622  xsd__date = #import "custom/qdate.h"
623 
624 After running wsdl2h and soapcpp2, compile `custom/qdate.cpp` with your
625 project.
626 
627 🔝 [Back to table of contents](#)
628 
629 ### xsd:time {#qt-6}
630 
631 To use Qt QDate for `xsd:time`, add the following definition to
632 `typemap.dat`:
633 
634  xsd__time = #import "custom/qtime.h"
635 
636 After running wsdl2h and soapcpp2, compile `custom/qtime.cpp` with your
637 project.
638 
639 🔝 [Back to table of contents](#)
640 
641 Class/struct member additions {#typemap3}
642 -----------------------------
643 
644 All generated classes and structs can be augmented with additional
645 members such as methods, constructors and destructors, and private members:
646 
647  prefix__type = $ member-declaration
648 
649 For example, we can add method declarations and private members to a class, say
650 `ns__record` as follows:
651 
652  ns__record = $ ns__record(const ns__record &); // copy constructor
653  ns__record = $ void print(); // a print method
654  ns__record = $ private: int status; // a private member
655 
656 Note that method declarations cannot include any code, because soapcpp2's input
657 permits only type declarations, not code.
658 
659 🔝 [Back to table of contents](#)
660 
661 Replacing XSD types by equivalent alternatives {#typemap4}
662 ----------------------------------------------
663 
664 Type replacements can be given to replace one type entirely with another given
665 type:
666 
667  prefix__type1 == prefix__type2
668 
669 This replaces all `prefix__type1` by `prefix__type2` in the wsdl2h output.
670 
671 @warning Do not agressively replace types, because this can cause XML schema
672 validation to fail when a value-type mismatch is encountered in the XML input.
673 Therefore, only replace similar types with other similar types that are wider
674 (e.g. `short` by `int` and `float` by `double`).
675 
676 🔝 [Back to table of contents](#)
677 
678 The built-in typemap.dat variables $CONTAINER and $POINTER {#typemap5}
679 ----------------------------------------------------------
680 
681 The `typemap.dat` `$CONTAINER` variable defines the container to emit in the
682 generated declarations, which is `std::vector` by default. For example, to emit
683 `std::list` as the container in the wsdl2h-generated declarations:
684 
685  $CONTAINER = std::list
686 
687 The `typemap.dat` `$POINTER` variable defines the smart pointer to emit in the
688 generated declarations, which replaces the use of `*` pointers. For example:
689 
690  $POINTER = std::shared_ptr
691 
692 Not all pointers in the generated output can be replaced by smart pointers.
693 Regular pointers are still used as union members and for pointers to arrays of
694 objects.
695 
696 @note The standard smart pointer `std::shared_ptr` is generally safe to use.
697 Other smart pointers such as `std::unique_ptr` and `std::auto_ptr` may cause
698 compile-time errors when classes have smart pointer members but no copy
699 constructor (a default copy constructor). A copy constructor is required for
700 non-shared smart pointer copying or swapping.
701 
702 Alternatives to `std::shared_ptr` of the form `NAMESPACE::shared_ptr` can be
703 assigned to `$POINTER` when the namespace `NAMESPACE` also implements
704 `NAMESPACE::make_shared` and when the shared pointer class provides `reset()`
705 and`get()` methods and the dereference operator. For example Boost
706 `boost::shared_ptr`:
707 
708  [
709  #include <boost/shared_ptr.hpp>
710  ]
711  $POINTER = boost::shared_ptr
712 
713 The user-defined content between `[` and `]` ensures that we include the Boost
714 header files that are needed to support `boost::shared_ptr` and
715 `boost::make_shared`.
716 
717 A Qt container can be used instead of the default `std::vector`, for example
718 `QVector`:
719 
720  [
721  #include <QVector>
722  ]
723  $CONTAINER = QVector
724 
725 🔝 [Back to table of contents](#)
726 
727 User-defined content {#typemap6}
728 --------------------
729 
730 Any other content to be generated by wsdl2h can be included in `typemap.dat` by
731 enclosing it within brackets `[` and `]` anywhere in the `typemap.dat` file.
732 Each of the two brackets MUST appear at the start of a new line.
733 
734 For example, we can add an `#import "wsa5.h"` to the wsdl2h-generated output as
735 follows:
736 
737  [
738  #import "import/wsa5.h"
739  ]
740 
741 which emits the `#import "import/wsa5.h"` literally at the start of the
742 wsdl2h-generated header file.
743 
744 🔝 [Back to table of contents](#)
745 
746 Mapping C/C++ to XML schema {#toxsd}
747 ===========================
748 
749 The soapcpp2 command generates the data binding implementation code from a data
750 binding interface `file.h`:
751 
752  soapcpp2 [options] file.h
753 
754 where `file.h` is a gSOAP header file that declares the XML data binding
755 interface. The `file.h` is typically generated by wsdl2h, but you can also
756 declare one yourself. If so, add `//gsaop` [directives](#directives) and
757 declare in this file all our C/C++ types you want to serialize in XML.
758 
759 You can also declare functions that will be converted to Web service operations
760 by soapcpp2. Global function declarations define service operations, which are
761 of the form:
762 
763 ```cpp
764 int prefix__func(arg1, arg2, ..., argn, result);
765 ```
766 
767 where `arg1`, `arg2`, ..., `argn` are formal argument declarations of the input
768 and `result` is a formal argument for the output, which must be a pointer or
769 reference to the result object to be populated. More information can be found
770 in the [gSOAP user guide.](http://www.genivia.com/doc/soapdoc2.html)
771 
772 🔝 [Back to table of contents](#)
773 
774 Overview of serializable C/C++ types {#toxsd1}
775 ------------------------------------
776 
777 The following C/C++ types are supported by soapcpp2 and mapped to XSD types
778 and constructs. See the subsections below for more details or follow the links.
779 
780 🔝 [Back to table of contents](#)
781 
782 ### List of Boolean types
783 
784 | Boolean Type | Notes |
785 | ----------------------------- | ----------------------------------------------------------------------------------- |
786 | `bool` | C++ bool |
787 | `enum xsd__boolean` | C alternative to C++ `bool` with `false_` and `true_` |
788 
789 @see Section [C++ bool and C alternative](#toxsd3).
790 
791 🔝 [Back to table of contents](#)
792 
793 ### List of enumeration and bitmask types
794 
795 | Enumeration Type | Notes |
796 | ----------------------------- | ----------------------------------------------------------------------------------- |
797 | `enum` | enumeration |
798 | `enum class` | C++11 scoped enumeration (soapcpp2 `-c++11`) |
799 | `enum*` | a bitmask that enumerates values 1, 2, 4, 8, ... |
800 | `enum* class` | C++11 scoped enumeration bitmask (soapcpp2 `-c++11`) |
801 
802 @see Section [enumerations and bitmasks](#toxsd4).
803 
804 🔝 [Back to table of contents](#)
805 
806 ### List of numerical types
807 
808 | Numerical Type | Notes |
809 | ----------------------------- | ----------------------------------------------------------------------------------- |
810 | `char` | byte |
811 | `short` | 16 bit integer |
812 | `int` | 32 bit integer |
813 | `long` | 32 bit integer |
814 | `LONG64` | 64 bit integer |
815 | `xsd__integer` | 128 bit integer, use `#import "custom/int128.h"` |
816 | `long long` | same as `LONG64` |
817 | `unsigned char` | unsigned byte |
818 | `unsigned short` | unsigned 16 bit integer |
819 | `unsigned int` | unsigned 32 bit integer |
820 | `unsigned long` | unsigned 32 bit integer |
821 | `ULONG64` | unsigned 64 bit integer |
822 | `unsigned long long` | same as `ULONG64` |
823 | `int8_t` | same as `char` |
824 | `int16_t` | same as `short` |
825 | `int32_t` | same as `int` |
826 | `int64_t` | same as `LONG64` |
827 | `uint8_t` | same as `unsigned char` |
828 | `uint16_t` | same as `unsigned short` |
829 | `uint32_t` | same as `unsigned int` |
830 | `uint64_t` | same as `ULONG64` |
831 | `size_t` | transient type (not serializable) |
832 | `float` | 32 bit float |
833 | `double` | 64 bit float |
834 | `long double` | extended precision float, use `#import "custom/long_double.h"` |
835 | `xsd__decimal` | `<quadmath.h>` 128 bit quadruple precision float, use `#import "custom/float128.h"` |
836 | `typedef` | declares a type name, with optional value range and string length bounds |
837 
838 @see Section [numerical types](#toxsd5).
839 
840 🔝 [Back to table of contents](#)
841 
842 ### List of string types
843 
844 | String Type | Notes |
845 | ----------------------------- | ----------------------------------------------------------------------------------- |
846 | `char*` | string (may contain UTF-8 with flag `SOAP_C_UTFSTRING`) |
847 | `wchar_t*` | wide string |
848 | `std::string` | C++ string (may contain UTF-8 with flag `SOAP_C_UTFSTRING`) |
849 | `std::wstring` | C++ wide string |
850 | `char[N]` | fixed-size string, requires soapcpp2 option `-b` |
851 | `_QName` | normalized QName content |
852 | `_XML` | literal XML string content with wide characters in UTF-8 |
853 | `typedef` | declares a new string type name, may restrict string length |
854 
855 @see Section [string types](#toxsd6).
856 
857 🔝 [Back to table of contents](#)
858 
859 ### List of date and time types
860 
861 | Date and Time Type | Notes |
862 | --------------------------------------- | ------------------------------------------------------------------------- |
863 | `time_t` | date and time point since epoch |
864 | `struct tm` | date and time point, use `#import "custom/struct_tm.h"` |
865 | `struct tm` | date point, use `#import "custom/struct_tm_date.h"` |
866 | `struct timeval` | date and time point, use `#import "custom/struct_timeval.h"` |
867 | `unsigned long long` | time point in microseconds, use `#import "custom/long_time.h"` |
868 | `std::chrono::system_clock::time_point` | date and time point, use `#import "custom/chrono_time_point.h"` |
869 
870 @see Section [date and time types](#toxsd7).
871 
872 🔝 [Back to table of contents](#)
873 
874 ### List of time duration types
875 
876 | Time Duration Type | Notes |
877 | ----------------------------- | ----------------------------------------------------------------------------------- |
878 | `long long` | duration in milliseconds, use `#import "custom/duration.h"` |
879 | `std::chrono::nanoseconds` | duration in nanoseconds, use `#import "custom/chrono_duration.h"` |
880 
881 @see Section [time duration types](#toxsd8).
882 
883 🔝 [Back to table of contents](#)
884 
885 ### List of classes and structs
886 
887 | Classes, Structs, and Members | Notes |
888 | ----------------------------- | ----------------------------------------------------------------------------------- |
889 | `class` | C++ class with single inheritance only |
890 | `struct` | C struct or C++ struct without inheritance |
891 | `std::shared_ptr<T>` | C++11 smart shared pointer |
892 | `std::unique_ptr<T>` | C++11 smart pointer |
893 | `std::auto_ptr<T>` | C++ smart pointer |
894 | `std::deque<T>` | use `#import "import/stldeque.h"` |
895 | `std::list<T>` | use `#import "import/stllist.h"` |
896 | `std::vector<T>` | use `#import "import/stlvector.h"` |
897 | `std::set<T>` | use `#import "import/stlset.h"` |
898 | `template<T> class` | a container with `begin()`, `end()`, `size()`, `clear()`, and `insert()` methods |
899 | `T*` | data member: pointer to data of type `T` or points to array of `T` of size `__size` |
900 | `T[N]` | data member: fixed-size array of type `T` |
901 | `union` | data member: requires a variant selector member `__union` |
902 | `void*` | data member: requires a `__type` member to indicate the type of object pointed to |
903 
904 @see Section [classes and structs](#toxsd9).
905 
906 🔝 [Back to table of contents](#)
907 
908 ### List of special classes and structs
909 
910 | Special Classes and Structs | Notes |
911 | ----------------------------- | ----------------------------------------------------------------------------------- |
912 | Special Array class/struct | single and multidimensional SOAP Arrays |
913 | Special Wrapper class/struct | complexTypes with simpleContent, wraps `__item` member |
914 | `xsd__hexBinary` | binary content |
915 | `xsd__base64Binary` | binary content and optional MIME/MTOM attachments |
916 | `xsd__anyType` | DOM elements, use `#import "dom.h"` |
917 | `@xsd__anyAttribute` | DOM attributes, use `#import "dom.h"` |
918 
919 @see Section [special classes and structs](#toxsd10).
920 
921 🔝 [Back to table of contents](#)
922 
923 Colon notation versus name prefixing with XML tag name translation {#toxsd2}
924 ------------------------------------------------------------------
925 
926 To bind C/C++ type names to XSD types, a simple form of name prefixing is used
927 by the gSOAP tools by prepending the XML namespace prefix to the C/C++ type
928 name with a pair of undescrores. This also ensures that name clashes cannot
929 occur when multiple WSDL and XSD files are converted to C/C++. Also, C++
930 namespaces are not sufficiently rich to capture XML schema namespaces
931 accurately, for example when class members are associated with schema elements
932 defined in another XML namespace and thus the XML namespace scope of the
933 member's name is relevant, not just its type.
934 
935 However, from a C/C++ centric point of view this can be cumbersome. Therefore,
936 colon notation is an alternative to physically augmenting C/C++ names with
937 prefixes.
938 
939 For example, the following class uses colon notation to bind the `record` class
940 to the `urn:types` schema:
941 
942 ```cpp
943 //gsoap ns schema namespace: urn:types
944 class ns:record // binding 'ns:' to a type name
945 {
946  public:
947  std::string name;
948  uint64_t SSN;
949  ns:record *spouse; // using 'ns:' with the type name
950  ns:record(); // using 'ns:' here too
951  ~ns:record(); // and here
952 };
953 ```
954 
955 The colon notation is stripped away by soapcpp2 when generating the data
956 binding implementation code for our project. So the final code just uses
957 `record` to identify this class and its constructor/destructor.
958 
959 When using colon notation make sure to be consistent and not use colon notation
960 mixed with prefixed forms. The name `ns:record` differs from `ns__record`,
961 because `ns:record` is compiled to an unqualified `record` name.
962 
963 Colon notation also facilitates overruling the elementFormDefault and
964 attributeFormDefault declaration that is applied to local elements and
965 attributes, when declared as members of classes, structs, and unions. For more
966 details, see [qualified and unqualified members](#toxsd9-6).
967 
968 A C/C++ identifier name (a type name, member name, function name, or parameter
969 name) is translated to an XML tag name by the following rules:
970 
971 - Two leading underscores indicates that the identifier name has no XML tag
972  name, i.e. this name is not visible in XML and is not translated.
973 - A leading underscore is removed, but the underscore indicates that: **a**) a
974  struct/class member name or parameter name has a wildcard XML tag name (i.e.
975  matches any XML tag), or **b**) a type name that has a
976  [document root element definition](#toxsd9-7).
977 - Trailing underscores are removed (i.e. trailing underscores can be used to
978  avoid name clashes with keywords).
979 - Underscores within names are translated to hyphens (hyphens are more common
980  in XML tags).
981 - `_USCORE` is translated to an underscore in the translated XML tag name.
982 - `_DOT` is translated to a dot (`.`) in the translated XML tag name.
983 - `_xHHHH` is translated to the Unicode character with code point HHHH (hex).
984 - C++11 Unicode identifier name characters in UTF-8 are translated as-is.
985 
986 For example, the C/C++ namespace qualified identifier name `s_a__my_way` is
987 translated to the XML tag name `s-a:my-way` by translating the prefix `s_a`
988 and the local name `my_way`.
989 
990 Struct/class member and parameter name translation can be overruled by using
991 [backtick XML tags](#toxsd9-5) (with gSOAP 2.8.30 and later versions).
992 
993 🔝 [Back to table of contents](#)
994 
995 C++ Bool and C alternatives {#toxsd3}
996 ---------------------------
997 
998 The C++ `bool` type is bound to built-in XSD type `xsd:boolean`.
999 
1000 The C alternative is to define an enumeration:
1001 
1002 ```cpp
1003 enum xsd__boolean { false_, true_ };
1004 ```
1005 
1006 or by defining an enumeration in C with pseudo-scoped enumeration constants:
1007 
1008 ```cpp
1009 enum xsd__boolean { xsd__boolean__false, xsd__boolean__true };
1010 ```
1011 
1012 The XML value space of these types is `false` and `true`, but also accepted
1013 are `0` and `1` values for false and true, respectively.
1014 
1015 To prevent name clashes, `false_` and `true_` have an underscore. Trailing
1016 underscores are removed from the XML value space.
1017 
1018 🔝 [Back to table of contents](#)
1019 
1020 Enumerations and bitmasks {#toxsd4}
1021 -------------------------
1022 
1023 Enumerations are mapped to XSD simpleType enumeration restrictions of
1024 `xsd:string`, `xsd:QName`, and `xsd:long`.
1025 
1026 Consider for example:
1027 
1028 ```cpp
1029 enum ns__Color { RED, WHITE, BLUE };
1030 ```
1031 
1032 which maps to a simpleType restriction of `xsd:string` in the soapcpp2-generated
1033 schema:
1034 
1035 <div class="alt">
1036 ```xml
1037 <simpleType name="Color">
1038  <restriction base="xsd:string">
1039  <enumeration value="RED"/>
1040  <enumeration value="WHITE"/>
1041  <enumeration value="BLUE"/>
1042  </restriction>
1043 </simpleType>
1044 ```
1045 </div>
1046 
1047 Enumeration name constants can be pseudo-scoped to prevent name clashes,
1048 because enumeration name constants have a global scope in C and C++:
1049 
1050 ```cpp
1051 enum ns__Color { ns__Color__RED, ns__Color__WHITE, ns__Color__BLUE };
1052 ```
1053 
1054 You can also use C++11 scoped enumerations to prevent name clashes:
1055 
1056 ```cpp
1057 enum class ns__Color : int { RED, WHITE, BLUE };
1058 ```
1059 
1060 Here, the enumeration class base type `: int` is optional. In place of `int`
1061 in the example above, we can also use `int8_t`, `int16_t`, `int32_t`, or
1062 `int64_t`.
1063 
1064 The XML value space of the enumertions defined above is `RED`, `WHITE`, and
1065 `BLUE`.
1066 
1067 Prefix-qualified enumeration name constants are mapped to simpleType
1068 restrictions of `xsd:QName`, for example:
1069 
1070 ```cpp
1071 enum ns__types { xsd__int, xsd__float };
1072 ```
1073 
1074 which maps to a simpleType restriction of `xsd:QName` in the soapcpp2-generated
1075 schema:
1076 
1077 <div class="alt">
1078 ```xml
1079 <simpleType name="types">
1080  <restriction base="xsd:QName">
1081  <enumeration value="xsd:int"/>
1082  <enumeration value="xsd:float"/>
1083  </restriction>
1084 </simpleType>
1085 ```
1086 </div>
1087 
1088 Enumeration name constants can be pseudo-numeric as follows:
1089 
1090 ```cpp
1091 enum ns__Primes { _3 = 3, _5 = 5, _7 = 7, _11 = 11 };
1092 ```
1093 
1094 which maps to a simpleType restriction of `xsd:long`:
1095 
1096 <div class="alt">
1097 ```xml
1098 <simpleType name="Color">
1099  <restriction base="xsd:long">
1100  <enumeration value="3"/>
1101  <enumeration value="5"/>
1102  <enumeration value="7"/>
1103  <enumeration value="11"/>
1104  </restriction>
1105 </simpleType>
1106 ```
1107 </div>
1108 
1109 The XML value space of this type is `3`, `5`, `7`, and `11`.
1110 
1111 Besides (pseudo-) scoped enumerations, another way to prevent name clashes
1112 accross enumerations is to start an enumeration name constant with one
1113 underscore or followed it by any number of underscores, which makes it
1114 unique. The leading and trailing underscores are removed from the XML value
1115 space.
1116 
1117 ```cpp
1118 enum ns__ABC { A, B, C };
1119 enum ns__BA { B, A }; // BAD: B = 1 but B is already defined as 2
1120 enum ns__BA_ { B_, A_ }; // OK
1121 ```
1122 
1123 The gSOAP soapcpp2 tool permits reusing enumeration name constants across
1124 (non-scoped) enumerations as long as these values are assigned the same
1125 constant. Therefore, the following is permitted:
1126 
1127 ```cpp
1128 enum ns__Primes { _3 = 3, _5 = 5, _7 = 7, _11 = 11 };
1129 enum ns__Throws { _1 = 1, _2 = 2, _3 = 3, _4 = 4, _5 = 5, _6 = 6 };
1130 ```
1131 
1132 A bitmask type is an `enum*` "product" enumeration with a geometric,
1133 power-of-two sequence of values assigned to the enumeration constants:
1134 
1135 ```cpp
1136 enum* ns__Options { SSL3, TLS10, TLS11, TLS12 };
1137 ```
1138 
1139 where the product enum assigns 1 to `SSL3`, 2 to `TLS10`, 4 to `TLS11`, and 8
1140 to `TLS12`, which allows these enumeration constants to be used in composing
1141 bitmasks with `|` (bitwise or) `&` (bitwise and), and `~` (bitwise not):
1142 
1143 ```cpp
1144 enum ns__Options options = (enum ns__Options)(SSL3 | TLS10 | TLS11 | TLS12);
1145 if (options & SSL3) // if SSL3 is an option, warn and remove from options
1146 {
1147  warning();
1148  options &= ~SSL3;
1149 }
1150 ```
1151 
1152 The bitmask type maps to a simpleType list restriction of `xsd:string` in the
1153 soapcpp2-generated schema:
1154 
1155 <div class="alt">
1156 ```xml
1157 <simpleType name="Options">
1158  <list>
1159  <restriction base="xsd:string">
1160  <enumeration value="SSL3"/>
1161  <enumeration value="TLS10"/>
1162  <enumeration value="TLS11"/>
1163  <enumeration value="TLS12"/>
1164  </restriction>
1165  </list>
1166 </simpleType>
1167 ```
1168 </div>
1169 
1170 The XML value space of this type consists of all 16 possible subsets of the
1171 four values, represented by an XML string with space-separated values. For
1172 example, the bitmask `TLS10 | TLS11 | TLS12` equals 14 and is represented by
1173 the XML string `TLS10 TLS11 TLS12`.
1174 
1175 You can also use C++11 scoped enumerations with bitmasks:
1176 
1177 ```cpp
1178 enum* class ns__Options { SSL3, TLS10, TLS11, TLS12 };
1179 ```
1180 
1181 The base type of a scoped enumeration bitmask, when explicitly given, is
1182 ignored. The base type is either `int` or `int64_t`, depending on the number
1183 of constants enumerated in the bitmask.
1184 
1185 To convert `enum` name constants and bitmasks to a string, we use the
1186 auto-generated function for enum `T`:
1187 
1188 ```cpp
1189 const char *soap_T2s(struct soap*, enum T val)
1190 ```
1191 
1192 The string returned is stored in an internal buffer of the current `soap`
1193 context, so you MUST copy it to keep it from being overwritten. For example,
1194 use `char *soap_strdup(struct soap*, const char*)`.
1195 
1196 To convert a string to an `enum` constant or bitmask, we use the auto-generated
1197 function
1198 
1199 ```cpp
1200 int soap_s2T(struct soap*, const char *str, enum T *val)
1201 ```
1202 
1203 This function takes the name (or names, space-separated for bitmasks) of
1204 the enumeration constant in a string `str`. Names should be given without the
1205 pseudo-scope prefix and without trailing underscores. The function sets `val`
1206 to the corresponding integer enum constant or to a bitmask. The function
1207 returns `SOAP_OK` (zero) on success or an error if the string is not a valid
1208 enumeration name.
1209 
1210 🔝 [Back to table of contents](#)
1211 
1212 Numerical types {#toxsd5}
1213 ---------------
1214 
1215 Integer and floating point types are mapped to the equivalent built-in XSD
1216 types with the same sign and bit width.
1217 
1218 The `size_t` type is transient (not serializable) because its width is platform
1219 dependent. We recommend to use `uint64_t` instead.
1220 
1221 The XML value space of integer types are their decimal representations without
1222 loss of precision.
1223 
1224 The XML value space of floating point types are their decimal representations.
1225 The decimal representations are formatted with the printf format string "%.9G"
1226 for floats and the printf format string "%.17lG" for double. To change the
1227 format strings, we can assign new strings to the following `struct soap`
1228 context members:
1229 
1230 ```cpp
1231 soap.float_format = "%g";
1232 soap.double_format = "%lg";
1233 soap.long_double_format = "%Lg";
1234 ```
1235 
1236 Note that decimal representations may result in a loss of precision of the
1237 least significant decimal. Therefore, the format strings that are used by
1238 default are sufficiently precise to avoid loss, but this may result in long
1239 decimal fractions in the XML value space.
1240 
1241 The `long double` extended floating point type requires a custom serializer:
1242 
1243 ```cpp
1244 #import "custom/long_double.h"
1245 ... use long double ...
1246 ```
1247 
1248 You can now use `long double`, which has a serializer that serializes this type
1249 as `xsd:decimal`. Compile and link your code with `custom/long_double.c`.
1250 
1251 The value space of floating point values includes the special values `INF`,
1252 `-INF`, and `NaN`. You can check a value for plus or minus infinity and
1253 not-a-number as follows:
1254 
1255 ```cpp
1256 soap_isinf(x) && x > 0 // is x INF?
1257 soap_isinf(x) && x < 0 // is x -INF?
1258 soap_isnan(x) // is x NaN?
1259 ```
1260 
1261 To assign these values, use:
1262 
1263 ```cpp
1264 // x is float // x is double, long double, or __float128
1265 x = FLT_PINFY; x = DBL_PINFTY;
1266 x = FLT_NINFY; x = DBL_NINFTY;
1267 x = FLT_NAN; x = DBL_NAN;
1268 ```
1269 
1270 If your system supports `__float128` then you can also use this 128 bit
1271 floating point type with a custom serializer:
1272 
1273 ```cpp
1274 #import "custom/float128.h"
1275 ... use xsd__decimal ...
1276 ```
1277 
1278 Then use the `xsd__decimal` alias of `__float128`, which has a serializer. Do
1279 not use `__float128` directly, which is transient (not serializable).
1280 
1281 To check for `INF`, `-INF`, and `NaN` of a `__float128` value use:
1282 
1283 ```cpp
1284 isinfq(x) && x > 0 // is x INF?
1285 isinfq(x) && x < 0 // is x -INF?
1286 isnanq(x) // is x NaN?
1287 ```
1288 
1289 The range of a typedef-defined numerical type can be restricted using the range
1290 `:` operator with inclusive lower and upper bounds. For example:
1291 
1292 ```cpp
1293 typedef int ns__narrow -10 : 10;
1294 ```
1295 
1296 This maps to a simpleType restriction of `xsd:int` in the soapcpp2-generated
1297 schema:
1298 
1299 <div class="alt">
1300 ```xml
1301 <simpleType name="narrow">
1302  <restriction base="xsd:int">
1303  <minInclusive value="-10"/>
1304  <maxInclusive value="10"/>
1305  </restriction>
1306 </simpleType>
1307 ```
1308 </div>
1309 
1310 The lower and upper bound of a range are optional. When omitted, values are
1311 not bound from below or from above, respectively.
1312 
1313 The range of a floating point typedef-defined type can be restricted within
1314 floating point constant bounds.
1315 
1316 Also with a floating point typedef a printf format pattern can be given of the
1317 form `"%[width][.precision]f"` to format decimal values using the given width
1318 and precision fields:
1319 
1320 ```cpp
1321 typedef float ns__PH "%5.2f" 0.0 : 14.0;
1322 ```
1323 
1324 This maps to a simpleType restriction of `xsd:float` in the soapcpp2-generated
1325 schema:
1326 
1327 <div class="alt">
1328 ```xml
1329 <simpleType name="PH">
1330  <restriction base="xsd:float">
1331  <totalDigits value="5"/>
1332  <fractionDigits value="2"/>
1333  <minInclusive value="0"/>
1334  <maxInclusive value="14"/>
1335  </restriction>
1336 </simpleType>
1337 ```
1338 </div>
1339 
1340 For exclusive bounds, we use the `<` operator instead of the `:` range
1341 operator:
1342 
1343 ```cpp
1344 typedef float ns__epsilon 0.0 < 1.0;
1345 ```
1346 
1347 Values `eps` of `ns__epsilon` are restricted between `0.0 < eps < 1.0`.
1348 
1349 This maps to a simpleType restriction of `xsd:float` in the soapcpp2-generated
1350 schema:
1351 
1352 <div class="alt">
1353 ```xml
1354 <simpleType name="epsilon">
1355  <restriction base="xsd:float">
1356  <minExclusive value="0"/>
1357  <maxExclusive value="1"/>
1358  </restriction>
1359 </simpleType>
1360 ```
1361 </div>
1362 
1363 To make just one of the bounds exclusive, while keeping the other bound
1364 inclusive, we add a `<` on the left or on the right side of the range ':'
1365 operator. For example:
1366 
1367 ```cpp
1368 typedef float ns__pos 0.0 < : ; // 0.0 < pos
1369 typedef float ns__neg : < 0.0 ; // neg < 0.0
1370 ```
1371 
1372 It is valid to make both left and right side exclusive with `< : <` which is in
1373 fact identical to the exlusive range `<` operator:
1374 
1375 ```cpp
1376 typedef float ns__epsilon 0.0 < : < 1.0; // 0.0 < eps < 1.0
1377 ```
1378 
1379 It helps to think of the `:` as a placeholder of the value between the two
1380 bounds, which is easier to memorize than the shorthand forms of bounds from
1381 which the `:` is removed:
1382 
1383 | Bounds | Validation Check | Shorthand |
1384 | ---------- | ---------------- | --------- |
1385 | 1 : | 1 <= x | 1 |
1386 | 1 : 10 | 1 <= x <= 10 | |
1387 | : 10 | x <= 10 | |
1388 | 1 < : < 10 | 1 < x < 10 | 1 < 10 |
1389 | 1 : < 10 | 1 <= x < 10 | |
1390 | : < 10 | x < 10 | < 10 |
1391 | 1 < : | 1 < x | 1 < |
1392 | 1 < : 10 | 1 < x <= 10 | |
1393 
1394 Besides `float`, also `double` and `long double` values can be restricted. For
1395 example, consider a nonzero probability extended floating point precision type:
1396 
1397 ```cpp
1398 #import "custom/long_double.h"
1399 typedef long double ns__probability "%16Lg" 0.0 < : 1.0;
1400 ```
1401 
1402 Value range restrictions are validated by the parser for all inbound XML data.
1403 A type fault `SOAP_TYPE` will be thrown by the deserializer if the value is out
1404 of range.
1405 
1406 Finally, if your system supports `__int128_t` then you can also use this 128
1407 bit integer type with a custom serializer:
1408 
1409 ```cpp
1410 #import "custom/int128.h"
1411 ... use xsd__integer ...
1412 ```
1413 
1414 Use the `xsd__integer` alias of `__int128_t`, which has a serializer. Do not
1415 use `__int128_t` directly, which is transient (not serializable).
1416 
1417 To convert numeric values to a string, we use the auto-generated function for
1418 numeric type `T`:
1419 
1420 ```cpp
1421 const char *soap_T2s(struct soap*, T val)
1422 ```
1423 
1424 For numeric types `T`, the string returned is stored in an internal buffer of
1425 the current `soap` context, so you MUST copy it to keep it from being
1426 overwritten. For example, use `char *soap_strdup(struct soap*, const char*)`.
1427 
1428 To convert a string to a numeric value, we use the auto-generated function
1429 
1430 ```cpp
1431 int soap_s2T(struct soap*, const char *str, T *val)
1432 ```
1433 
1434 where `T` is for example `int`, `LONG64`, `float`, `decimal` (the custom
1435 serializer name of `long double`) or `xsd__integer` (the custom serializer name
1436 of `__int128_t`). The function `soap_s2T` returns `SOAP_OK` on success or an
1437 error when the value is not numeric. For floating point types, "INF", "-INF"
1438 and "NaN" are valid strings to convert to numbers.
1439 
1440 🔝 [Back to table of contents](#)
1441 
1442 String types {#toxsd6}
1443 ------------
1444 
1445 String types are mapped to the built-in `xsd:string` and `xsd:QName` XSD types.
1446 
1447 The wide strings `wchar_t*` and `std::wstring` may contain Unicode that is
1448 preserved in the XML value space.
1449 
1450 Strings `char*` and `std::string` can only contain extended Latin, but we can
1451 store UTF-8 content that is preserved in the XML value space when the `struct
1452 soap` context is initialized with the flag `SOAP_C_UTFSTRING`.
1453 
1454 @warning Beware that many XML 1.0 parsers reject all control characters (those
1455 between `#x1` and `#x1F`) except for `#x9`, `#xA`, and `#xD`. With the
1456 newer XML 1.1 version parsers (including gSOAP) you should be fine.
1457 
1458 The length of a string of a typedef-defined string type can be restricted:
1459 
1460 ```cpp
1461 typedef std::string ns__password 6 : 16;
1462 ```
1463 
1464 which maps to a simpleType restriction of `xsd:string` in the soapcpp2-generated
1465 schema:
1466 
1467 <div class="alt">
1468 ```xml
1469 <simpleType name="password">
1470  <restriction base="xsd:string">
1471  <minLength value="6"/>
1472  <maxLength value="16"/>
1473  </restriction>
1474 </simpleType>
1475 ```
1476 </div>
1477 
1478 String length restrictions are validated by the parser for inbound XML data.
1479 A value length fault `SOAP_LENGTH` will be thrown by the deserializer if the
1480 string is too long or too short.
1481 
1482 In addition, an XSD regex pattern restriction can be associated with a string
1483 typedef:
1484 
1485 ```cpp
1486 typedef std::string ns__password "([a-zA-Z]|[0-9]|-)+" 6 : 16;
1487 ```
1488 
1489 which maps to a simpleType restriction of `xsd:string` in the soapcpp2-generated
1490 schema:
1491 
1492 <div class="alt">
1493 ```xml
1494 <simpleType name="password">
1495  <restriction base="xsd:string">
1496  <pattern value="([a-zA-Z0-9]|-)+"/>
1497  <minLength value="6"/>
1498  <maxLength value="16"/>
1499  </restriction>
1500 </simpleType>
1501 ```
1502 </div>
1503 
1504 Pattern restrictions are validated by the parser for inbound XML data only if
1505 the `soap::fsvalidate` and `soap::fwvalidate` callbacks are defined, see the
1506 [gSOAP user guide.](http://www.genivia.com/doc/soapdoc2.html)
1507 
1508 Exclusive length bounds can be used with strings:
1509 
1510 ```cpp
1511 typedef std::string ns__string255 : < 256; // same as 0 : 255
1512 ```
1513 
1514 Fixed-size strings (`char[N]`) are rare occurrences in the wild, but apparently
1515 still used in some projects to store strings. To facilitate fixed-size string
1516 serialization, use soapcpp2 option `-b`. For example:
1517 
1518 ```cpp
1519 typedef char ns__buffer[10]; // requires soapcpp2 option -b
1520 ```
1521 
1522 which maps to a simpleType restriction of `xsd:string` in the soapcpp2-generated
1523 schema:
1524 
1525 <div class="alt">
1526 ```xml
1527 <simpleType name="buffer">
1528  <restriction base="xsd:string">
1529  <maxLength value="9"/>
1530  </restriction>
1531 </simpleType>
1532 ```
1533 </div>
1534 
1535 Note that fixed-size strings MUST contain NUL-terminated text and SHOULD NOT
1536 contain raw binary data. Also, the length limitation is more restrictive for
1537 UTF-8 content (enabled with the `SOAP_C_UTFSTRING`) that requires multibyte
1538 character encodings. As a consequence, UTF-8 content may be truncated to fit.
1539 
1540 Note that raw binary data can be stored in a `xsd__base64Binary` or
1541 `xsd__hexBinary` structure, or transmitted as a MIME attachment.
1542 
1543 The built-in `_QName` type is a regular C string type (`char*`) that maps to
1544 `xsd:QName` but has the added advantage that it holds normalized qualified names.
1545 There are actually two forms of normalized QName content, to ensure any QName
1546 is represented accurately and uniquely:
1547 
1548 ```cpp
1549 "prefix:name"
1550 "\"URI\":name"
1551 ```
1552 
1553 The first form of string is used when the prefix (and the binding URI) is
1554 defined in the namespace table and is bound to a URI (see the .nsmap file).
1555 The second form is used when the URI is not defined in the namespace table and
1556 therefore no prefix is available to bind and normalize the URI to.
1557 
1558 A `_QName` string may contain a sequence of space-separated QName values, not
1559 just one, and all QName values are normalized to the format shown above.
1560 
1561 To define a `std::string` base type for `xsd:QName`, we use a typedef:
1562 
1563 ```cpp
1564 typedef std::string xsd__QName;
1565 ```
1566 
1567 The `xsd__QName` string content is normalized, just as with the `_QName`
1568 normalization.
1569 
1570 To serialize strings that contain literal XML content to be reproduced in the
1571 XML value space, use the built-in `_XML` string type, which is a regular C
1572 string type (`char*`) that maps to plain XML CDATA.
1573 
1574 To define a `std::string` base type for literal XML content, use a typedef:
1575 
1576 ```cpp
1577 typedef std::string XML;
1578 ```
1579 
1580 Strings can hold any of the values of the XSD built-in primitive types. We can
1581 use a string typedef to declare the use of the string type as a XSD built-in
1582 type:
1583 
1584 ```cpp
1585 typedef std::string xsd__token;
1586 ```
1587 
1588 You MUST ensure that the string values we populate in this type conform to the
1589 XML standard, which in case of `xsd:token` is the lexical and value spaces of
1590 `xsd:token` are the sets of all strings after whitespace replacement of any
1591 occurrence of `#x9`, `#xA` , and `#xD` by `#x20` and collapsing.
1592 
1593 To copy `char*` or `wchar_t*` strings with a context that manages the allocated
1594 memory, use functions
1595 
1596 ```cpp
1597 char *soap_strdup(struct soap*, const char*)
1598 wchar_t *soap_wstrdup(struct soap*, const wchar_t*)
1599 ```
1600 
1601 To convert a wide string to a UTF-8 encoded string, use function
1602 
1603 ```cpp
1604 const char* SOAP_FMAC2 soap_wchar2s(struct soap*, const wchar_t *s)
1605 ```
1606 
1607 The function allocates and returns a string, with its memory being managed by
1608 the context.
1609 
1610 To convert a UTF-8 encoded string to a wide string, use function
1611 
1612 ```cpp
1613 int soap_s2wchar(struct soap*, const char *from, wchar_t **to, long minlen, long maxlen)
1614 ```
1615 
1616 where `to` is set to point to an allocated `wchar_t*` string. Pass `-1` for
1617 `minlen` and `maxlen` to ignore length constraints on the target string. The
1618 function returns `SOAP_OK` or an error when the length constraints are not met.
1619 
1620 🔝 [Back to table of contents](#)
1621 
1622 Date and time types {#toxsd7}
1623 -------------------
1624 
1625 The C/C++ `time_t` type is mapped to the built-in `xsd:dateTime` XSD type that
1626 represents a date and time within a time zone (typically UTC).
1627 
1628 The XML value space contains ISO 8601 Gregorian time instances of the form
1629 `[-]CCYY-MM-DDThh:mm:ss.sss[Z|(+|-)hh:mm]`, where `Z` is the UTC time zone
1630 or a time zone offset `(+|-)hh:mm]` from UTC is used.
1631 
1632 A `time_t` value is considered and represented in UTC by the serializer.
1633 
1634 Because the `time_t` value range is restricted to dates after 01/01/1970 and
1635 before 2038 assuming `time_t` is a `long` 32 bit, care must be taken to ensure
1636 the range of `xsd:dateTime` values in XML exchanges do not exceed the `time_t`
1637 range.
1638 
1639 This restriction does not hold for `struct tm` (`<time.h>`), which we can use
1640 to store and exchange a date and time in UTC without date range restrictions.
1641 The serializer uses the `struct tm` members directly for the XML value space of
1642 `xsd:dateTime`:
1643 
1644 ```cpp
1645 struct tm
1646 {
1647  int tm_sec; // seconds (0 - 60)
1648  int tm_min; // minutes (0 - 59)
1649  int tm_hour; // hours (0 - 23)
1650  int tm_mday; // day of month (1 - 31)
1651  int tm_mon; // month of year (0 - 11)
1652  int tm_year; // year - 1900
1653  int tm_wday; // day of week (Sunday = 0) (NOT USED)
1654  int tm_yday; // day of year (0 - 365) (NOT USED)
1655  int tm_isdst; // is summer time in effect?
1656  char* tm_zone; // abbreviation of timezone (NOT USED)
1657 };
1658 ```
1659 
1660 You will lose the day of the week information. It is always Sunday
1661 (`tm_wday=0`) and the day of the year is not set either. The time zone is UTC.
1662 
1663 This `struct tm` type is mapped to the built-in `xsd:dateTime` XSD type and
1664 serialized with the custom serializer `custom/struct_tm.h` that declares a
1665 `xsd__dateTime` type:
1666 
1667 ```cpp
1668 #import "custom/struct_tm.h" // import typedef struct tm xsd__dateTime;
1669 ... use xsd__dateTime ...
1670 ```
1671 
1672 Compile and link your code with `custom/struct_tm.c`.
1673 
1674 The `struct timeval` (`<sys/time.h>`) type is mapped to the built-in
1675 `xsd:dateTime` XSD type and serialized with the custom serializer
1676 `custom/struct_timeval.h` that declares a `xsd__dateTime` type:
1677 
1678 ```cpp
1679 #import "custom/struct_timeval.h" // import typedef struct timeval xsd__dateTime;
1680 ... use xsd__dateTime ...
1681 ```
1682 
1683 Compile and link your code with `custom/struct_timeval.c`.
1684 
1685 Note that the same value range restrictions apply to `struct timeval` as they
1686 apply to `time_t`. The added benefit of `struct timeval` is the addition of
1687 a microsecond-precise clock:
1688 
1689 ```cpp
1690 struct timeval
1691 {
1692  time_t tv_sec; // seconds since Jan. 1, 1970
1693  suseconds_t tv_usec; // and microseconds
1694 };
1695 ```
1696 
1697 A C++11 `std::chrono::system_clock::time_point` type is mapped to the built-in
1698 `xsd:dateTime` XSD type and serialized with the custom serializer
1699 `custom/chrono_time_point.h` that declares a `xsd__dateTime` type:
1700 
1701 ```cpp
1702 #import "custom/chrono_time_point.h" // import typedef std::chrono::system_clock::time_point xsd__dateTime;
1703 ... use xsd__dateTime ...
1704 ```
1705 
1706 Compile and link your code with `custom/chrono_time_point.cpp`.
1707 
1708 The `struct tm` type is mapped to the built-in `xsd:date` XSD type and serialized
1709 with the custom serializer `custom/struct_tm_date.h` that declares a
1710 `xsd__date` type:
1711 
1712 ```cpp
1713 #import "custom/struct_tm_date.h" // import typedef struct tm xsd__date;
1714 ... use xsd__date ...
1715 ```
1716 
1717 Compile and link your code with `custom/struct_tm_date.c`.
1718 
1719 The XML value space of `xsd:date` are Gregorian calendar dates of the form
1720 `[-]CCYY-MM-DD[Z|(+|-)hh:mm]` with a time zone.
1721 
1722 The serializer ignores the time part and the deserializer only populates the
1723 date part of the struct, setting the time to 00:00:00. There is no unreasonable
1724 limit on the date range because the year field is stored as an integer (`int`).
1725 
1726 An `unsigned long long` (`ULONG64` or `uint64_t`) type that contains a 24 hour
1727 time in microseconds UTC is mapped to the built-in `xsd:time` XSD type and
1728 serialized with the custom serializer `custom/long_time.h` that declares a
1729 `xsd__time` type:
1730 
1731 ```cpp
1732 #import "custom/long_time.h" // import typedef unsigned long long xsd__time;
1733 ... use xsd__time ...
1734 ```
1735 
1736 Compile and link your code with `custom/long_time.c`.
1737 
1738 This type represents `00:00:00.000000` to `23:59:59.999999`, from 0 to an
1739 upper bound of 86,399,999,999. A microsecond resolution means that a 1 second
1740 increment requires an increment of 1,000,000 in the integer value.
1741 
1742 The XML value space of `xsd:time` are points in time recurring each day of the
1743 form `hh:mm:ss.sss[Z|(+|-)hh:mm]`, where `Z` is the UTC time zone or a time
1744 zone offset from UTC is used. The `xsd__time` value is always considered and
1745 represented in UTC by the serializer.
1746 
1747 To convert date and/or time values to a string, we use the auto-generated
1748 function for type `T`:
1749 
1750 ```cpp
1751 const char *soap_T2s(struct soap*, T val)
1752 ```
1753 
1754 For date and time types `T`, the string returned is stored in an internal
1755 buffer of the current `soap` context, so you MUST copy it to keep it from being
1756 overwritten. For example, use `char *soap_strdup(struct soap*, const char*)`.
1757 
1758 To convert a string to a date/time value, we use the auto-generated function
1759 
1760 ```cpp
1761 int soap_s2T(struct soap*, const char *str, T *val)
1762 ```
1763 
1764 where `T` is for example `dateTime` (for `time_t`), `xsd__dateTime` (for
1765 `struct tm`, `struct timeval`, or `std::chrono::system_clock::time_point`).
1766 The function `soap_s2T` returns `SOAP_OK` on success or an error when the value
1767 is not a date/time.
1768 
1769 🔝 [Back to table of contents](#)
1770 
1771 Time duration types {#toxsd8}
1772 -------------------
1773 
1774 The XML value space of `xsd:duration` are values of the form `PnYnMnDTnHnMnS`
1775 where the capital letters are delimiters. Delimiters may be omitted when the
1776 corresponding member is not used.
1777 
1778 A `long long` (`LONG64` or `int64_t`) type that contains a duration (time
1779 lapse) in milliseconds is mapped to the built-in `xsd:duration` XSD type and
1780 serialized with the custom serializer `custom/duration.h` that declares a
1781 `xsd__duration` type:
1782 
1783 ```cpp
1784 #import "custom/duration.h" // import typedef long long xsd__duration;
1785 ... use xsd__duration ...
1786 ```
1787 
1788 Compile and link your code with `custom/duration.c`.
1789 
1790 The duration type `xsd__duration` can represent 106,751,991,167 days forward
1791 and backward with millisecond precision.
1792 
1793 Durations that exceed a month are always output in days, rather than months to
1794 avoid days-per-month conversion inacurracies.
1795 
1796 Durations that are received in years and months instead of total number of days
1797 from a reference point are not well defined, since there is no accepted
1798 reference time point (it may or may not be the current time). The decoder
1799 simple assumes that there are 30 days per month. For example, conversion of
1800 "P4M" gives 120 days. Therefore, the durations "P4M" and "P120D" are assumed
1801 to be identical, which is not necessarily true depending on the reference point
1802 in time.
1803 
1804 Rescaling of the duration value by may be needed when adding the duration value
1805 to a `time_t` value, because `time_t` may or may not have a seconds resolution,
1806 depending on the platform and possible changes to `time_t`.
1807 
1808 Rescaling is done automatically when you add a C++11 `std::chrono::nanoseconds`
1809 value to a `std::chrono::system_clock::time_point` value. To use
1810 `std::chrono::nanoseconds` as `xsd:duration`:
1811 
1812 ```cpp
1813 #import "custom/chrono_duration.h" // import typedef std::chrono::duration xsd__duration;
1814 ... use xsd__duration ...
1815 ```
1816 
1817 Compile and link your code with `custom/chrono_duration.cpp`.
1818 
1819 This type can represent 384,307,168 days (2^63 nanoseconds) forwards and
1820 backwards in time in increments of 1 ns (1/1000000000 second).
1821 
1822 The same observations with respect to receiving durations in years and months
1823 apply to this serializer's decoder.
1824 
1825 To convert duration values to a string, we use the auto-generated function
1826 
1827 ```cpp
1828 const char *soap_xsd__duration2s(struct soap*, xsd__duration val)
1829 ```
1830 
1831 The string returned is stored in an internal buffer, so you MUST copy it to
1832 keep it from being overwritten, Use `soap_strdup(struct soap*, const char*)`
1833 for example to copy this string.
1834 
1835 To convert a string to a duration value, we use the auto-generated function
1836 
1837 ```cpp
1838 int soap_s2xsd__dateTime(struct soap*, const char *str, xsd__dateTime *val)
1839 ```
1840 
1841 The function returns `SOAP_OK` on success or an error when the value is not a
1842 duration.
1843 
1844 🔝 [Back to table of contents](#)
1845 
1846 Classes and structs {#toxsd9}
1847 -------------------
1848 
1849 Classes and structs are mapped to XSD complexTypes. The XML value space
1850 consists of XML elements with attributes and subelements, possibly constrained
1851 by XML schema validation rules that enforce element and attribute occurrence
1852 contraints, numerical value range constraints, and string length and pattern
1853 constraints.
1854 
1855 Classes that are declared with the gSOAP tools are limited to single
1856 inheritence only. Structs cannot be inherited.
1857 
1858 The class and struct name is bound to an XML namespace by means of the prefix
1859 naming convention or by using [colon notation](#toxsd1):
1860 
1861 ```cpp
1862 //gsoap ns schema namespace: urn:types
1863 class ns__record
1864 {
1865  public:
1866  std::string name;
1867  uint64_t SSN;
1868  ns__record *spouse;
1869  ns__record();
1870  ~ns__record();
1871  protected:
1872  struct soap *soap;
1873 };
1874 ```
1875 
1876 In the example above, we also added a context pointer to the `struct soap` that
1877 manages this instance. It is set when the instance is created in the engine's
1878 context, for example when deserialized and populated by the engine.
1879 
1880 The class maps to a complexType in the soapcpp2-generated schema:
1881 
1882 <div class="alt">
1883 ```xml
1884 <complexType name="record">
1885  <sequence>
1886  <element name="name" type="xsd:string" minOccurs="1" maxOccurs="1"/>
1887  <element name="SSN" type="xsd:unsignedLong" minOccurs="1" maxOccurs="1"/>
1888  <element name="spouse" type="ns:record" minOccurs="0" maxOccurs="1" nillable="true"/>
1889  </sequence>
1890 </complexType>
1891 ```
1892 </div>
1893 
1894 🔝 [Back to table of contents](#)
1895 
1896 ### Serializable versus transient types and data members {#toxsd9-1}
1897 
1898 Public data members of a class or struct are serialized. Private and protected
1899 members are transient and not serializable.
1900 
1901 Also `const` and `static` members are not serializable, with the exception of
1902 `const char*` and `const wchar_t*`. Types and specific class/struct members
1903 can also be made transient with the `extern` qualifier:
1904 
1905 ```cpp
1906 extern class std::ostream; // declare 'std::ostream' transient
1907 class ns__record
1908 {
1909  public:
1910  extern int num; // not serialized
1911  std::ostream out; // not serialized
1912  static const int MAX = 1024; // not serialized
1913 };
1914 ```
1915 
1916 By declaring `std::ostream` transient with `extern` you can use this type
1917 wherever you need it without soapcpp2 complaining that this class is not
1918 defined.
1919 
1920 🔝 [Back to table of contents](#)
1921 
1922 ### Volatile classes and structs {#toxsd9-2}
1923 
1924 Classes and structs can be declared `volatile` with the gSOAP tools. This means
1925 that they are already declared elsewhere in your project's source code and you
1926 do not want soapcpp2 to generate code with a second declaration of these types.
1927 
1928 For example, `struct tm` is declared in `<time.h>`. You can make it serializable
1929 and include a partial list of data members that you want to serialize:
1930 
1931 ```cpp
1932 volatile struct tm
1933 {
1934  int tm_sec; // seconds (0 - 60)
1935  int tm_min; // minutes (0 - 59)
1936  int tm_hour; // hours (0 - 23)
1937  int tm_mday; // day of month (1 - 31)
1938  int tm_mon; // month of year (0 - 11)
1939  int tm_year; // year - 1900
1940 };
1941 ```
1942 
1943 You can declare classes and structs `volatile` for any such types you want to
1944 serialize by only providing the public data members you want to serialize.
1945 
1946 In addition, [colon notation](#toxsd2) is a simple and effective way to bind an
1947 existing class or struct to a schema. For example, you can change the `tm` name
1948 as follows without affecting the code that uses `struct tm` generated by
1949 soapcpp2:
1950 
1951 ```cpp
1952 volatile struct ns:tm { ... }
1953 ```
1954 
1955 This struct maps to a complexType in the soapcpp2-generated schema:
1956 
1957 <div class="alt">
1958 ```xml
1959 <complexType name="tm">
1960  <sequence>
1961  <element name="tm-sec" type="xsd:int" minOccurs="1" maxOccurs="1"/>
1962  <element name="tm-min" type="xsd:int" minOccurs="1" maxOccurs="1"/>
1963  <element name="tm-hour" type="xsd:int" minOccurs="1" maxOccurs="1"/>
1964  <element name="tm-mday" type="xsd:int" minOccurs="1" maxOccurs="1"/>
1965  <element name="tm-mon" type="xsd:int" minOccurs="1" maxOccurs="1"/>
1966  <element name="tm-year" type="xsd:int" minOccurs="1" maxOccurs="1"/>
1967  </sequence>
1968 </complexType>
1969 ```
1970 </div>
1971 
1972 🔝 [Back to table of contents](#)
1973 
1974 ### Mutable classes and structs {#toxsd9-3}
1975 
1976 Classes and structs can be declared `mutable` with the gSOAP tools. This means
1977 that their definition can be spread out over the source code. This promotes the
1978 concept of a class or struct as a *row of named values*, also known as a *named
1979 tuple*, that can be extended at compile time in your source code with additional
1980 members. Because these types differ from the traditional object-oriented
1981 principles and design concepts of classes and objects, constructors and
1982 destructors cannot be defined (also because we cannot guarantee merging these
1983 into one such that all members will be initialized). A default constructor,
1984 copy constructor, assignment operation, and destructor will be assigned
1985 automatically by soapcpp2.
1986 
1987 ```cpp
1988 mutable struct ns__tuple
1989 {
1990  @std::string id;
1991 };
1992 
1993 mutable struct ns__tuple
1994 {
1995  std::string name;
1996  std::string value;
1997 };
1998 ```
1999 
2000 The members are collected into one definition generated by soapcpp2. Members
2001 may be repeated from one definition to another, but only if their associated
2002 types are identical. So, for example, a third extension with a `value` member
2003 with a different type fails:
2004 
2005 ```cpp
2006 mutable struct ns__tuple
2007 {
2008  float value; // BAD: value is already declared std::string
2009 };
2010 ```
2011 
2012 The `mutable` concept has proven to be very useful when declaring and
2013 collecting SOAP Headers for multiple services, which are collected into one
2014 `struct SOAP_ENV__Header` by the soapcpp2 tool.
2015 
2016 🔝 [Back to table of contents](#)
2017 
2018 ### Default and fixed member values {#toxsd9-4}
2019 
2020 Class and struct data members in C and C++ may be declared with an optional
2021 default initialization value that is provided "inline" with the declaration of
2022 the member:
2023 
2024 ```cpp
2025 class ns__record
2026 {
2027  public:
2028  std::string name = "Joe";
2029  ...
2030 };
2031 ```
2032 
2033 Alternatively, use C++11 default initialization syntax:
2034 
2035 ```cpp
2036 class ns__record
2037 {
2038  public:
2039  std::string name { "Joe" };
2040  ...
2041 };
2042 ```
2043 
2044 These initializations are made by the default constructor that is added by
2045 soapcpp2 to each class and struct (in C++ only). A constructor is only added
2046 when a default constructor is not already defined with the class declaration.
2047 
2048 You can explicitly (re)initialize an object with these initial values by using
2049 the soapcpp2 auto-generated functions:
2050 
2051 - `void T::soap_default(struct soap*)` for `class T` (C++ only)
2052 - `void soap_default_T(struct soap*, T*)` for `struct T` (C and C++).
2053 
2054 Default value initializations can be provided for members that have primitive
2055 types (`bool`, `enum`, `time_t`, numeric and string types).
2056 
2057 Default value initializations of pointer members is permitted, but the effect
2058 is different. To conform to XML schema validation, an attribute member that is
2059 a pointer to a primitive type will be assigned the default value when parsed
2060 from XML. An element member that is a pointer to a primitive type will be
2061 assigned when the element is empty when parsed from XML.
2062 
2063 As of gSOAP 2.8.48 and greater, a fixed value can be assigned with a `==`. A
2064 fixed value is also verified by the parser's validator.
2065 
2066 Default and fixed values for members with or without pointers are best
2067 explained with the following two example fragments.
2068 
2069 A record class (can be a struct in C) with default values for attributes and
2070 elements is declared as follows:
2071 
2072 ```cpp
2073 class ns__record_with_default
2074 {
2075  public:
2076  @std::string a = "A"; // optional XML attribute with default value "A"
2077  @std::string b 1 = "B"; // required XML attribute with default value "B"
2078  @std::string *c = "C"; // optional XML attribute with default value "C"
2079  std::string d 0 = "D"; // optional XML element with default value "D"
2080  std::string e = "E"; // required XML element with default value "E"
2081  std::string *f = "F"; // optional XML element with default value "F"
2082  ...
2083 };
2084 ```
2085 
2086 Note that attributes are optional unless marked as required with the occurrence
2087 constraint `1`. Elements are required unless the member type is a pointer or
2088 if the member is marked optional with occurrence constraint `0`.
2089 
2090 Instead of default values, fixed values indicate that the attribute or element
2091 must contain that value, and only that value, when provided in XML. A fixed
2092 value is specified with a `==`.
2093 
2094 A record class (can be a struct in C) with fixed values for attributes and
2095 elements is declared as follows:
2096 
2097 ```cpp
2098 class ns__record_with_fixed
2099 {
2100  public:
2101  @std::string g == "G"; // optional XML attribute with fixed value "G"
2102  @std::string h 1 == "H"; // required XML attribute with fixed value "H"
2103  @std::string *i == "I"; // optional XML attribute with fixed value "I"
2104  std::string j 0 == "J"; // optional XML element with fixed value "J"
2105  std::string k == "K"; // required XML element with fixed value "K"
2106  std::string *l == "L"; // optional XML element with fixed value "L"
2107  ...
2108 };
2109 ```
2110 
2111 The XML schema validation rules for the two example classes above are as
2112 follows:
2113 
2114 Member | Notes
2115 ------ | ---------------------------------------------------------------------
2116 `a` | attribute may appear once; if it does not appear its value is "A", otherwise its value is that given (also note: instantiating `ns__record_with_default` assigns the default value "A")
2117 `b` | has no effect when parsing XML (but note: instantiating `ns__record_with_default` assigns the default value "B")
2118 `c` | attribute may appear once; if it does not appear its value is "C", otherwise its value is that given (also note: instantiating `ns__record_with_default` assigns NULL)
2119 `d` | element may appear once; if it does not appear or if it is empty, its value is "D"; otherwise its value is that given (also note: instantiating `ns__record_with_default` assigns the default value "D")
2120 `e` | has no effect when parsing XML (but note: instantiating `ns__record_with_default` assigns the default value "E")
2121 `f` | element may appear once; if it does not appear it is not provided; if it does appear and it is empty, its value is "F"; otherwise its value is that given (also note: instantiating `ns__record_with_default` assigns NULL)
2122 `g` | attribute may appear once; if it does not appear its value is "G", if it does not appear its value is "G" (also note: instantiating `ns__record_with_fixed` assigns the fixed value "G")
2123 `h` | attribute must appear once, its value must be "H" (also note: instantiating `ns__record_with_fixed` assigns the fixed value "H")
2124 `i` | attribute may appear once; if it does not appear its value is "I", if it does not appear its value is "I" (also note: instantiating `ns__record_with_fixed` assigns NULL)
2125 `j` | element may appear once, if it does not appear it is not provided; if it does appear and it is empty, its value is "J"; if it does appear and it is not empty, its value must be "J" (also note: instantiating `ns__record_with_fixed` assigns the fixed value "J")
2126 `k` | element must appear once, its value must be "K" (also note: instantiating `ns__record_with_fixed` assigns the fixed value "K")
2127 `l` | element may appear once, if it does not appear it is not provided; if it does appear and it is empty, its value is "J"; if it does appear and it is not empty, its value must be "J" (also note: instantiating `ns__record_with_fixed` assigns NULL)
2128 
2129 @see Section [operations on classes and structs](#toxsd9-13).
2130 
2131 🔝 [Back to table of contents](#)
2132 
2133 ### Attribute members and backtick XML tags {#toxsd9-5}
2134 
2135 Class and struct data members are declared as XML attributes by annotating
2136 their type with a `@` qualifier:
2137 
2138 ```cpp
2139 class ns__record
2140 {
2141  public:
2142  @std::string name;
2143  @uint64_t SSN;
2144  ns__record *spouse;
2145 };
2146 ```
2147 
2148 This class maps to a complexType in the soapcpp2-generated schema:
2149 
2150 <div class="alt">
2151 ```xml
2152 <complexType name="record">
2153  <sequence>
2154  <element name="spouse" type="ns:record" minOccurs="0" maxOccurs="1" nillable="true"/>
2155  </sequence>
2156  <attribute name="name" type="xsd:string" use="required"/>
2157  <attribute name="SSN" type="xsd:unsignedLong" use="required"/>
2158 </complexType>
2159 ```
2160 </div>
2161 
2162 An example XML instance of `ns__record` is:
2163 
2164 <div class="alt">
2165 ```xml
2166 <ns:record xmlns:ns="urn:types" name="Joe" SSN="1234567890">
2167  <spouse name="Jane" SSN="1987654320">
2168  </spouse>
2169 </ns:record>
2170 ```
2171 </div>
2172 
2173 Attribute data members are restricted to primitive types (`bool`, `enum`,
2174 `time_t`, numeric and string types), `xsd__hexBinary`, `xsd__base64Binary`, and
2175 custom serializers, such as `xsd__dateTime`. Custom serializers for types that
2176 may be used as attributes MUST define `soap_s2T` and `soap_T2s` functions that
2177 convert values of type `T` to strings and back.
2178 
2179 Attribute data members can be pointers and smart pointers to these types, which
2180 permits attributes to be optional.
2181 
2182 The XML tag name of a class/struct member is the name of the member with the
2183 usual XML tag translation, see [colon notation](#toxsd2).
2184 
2185 To override the standard translation of identifier names to XML tag names of
2186 attributes and elements, add the XML tag name in backticks (requires gSOAP
2187 2.8.30 and later versions):
2188 
2189 ```cpp
2190 class ns__record
2191 {
2192  public:
2193  @std::string name `full-name`;
2194  @uint64_t SSN `tax-id`;
2195  ns__record *spouse `married-to`;
2196 };
2197 ```
2198 
2199 This class maps to a complexType in the soapcpp2-generated schema:
2200 
2201 <div class="alt">
2202 ```xml
2203 <complexType name="record">
2204  <sequence>
2205  <element name="married-to" type="ns:record" minOccurs="0" maxOccurs="1" nillable="true"/>
2206  </sequence>
2207  <attribute name="full-name" type="xsd:string" use="required"/>
2208  <attribute name="tax-id" type="xsd:unsignedLong" use="required"/>
2209 </complexType>
2210 ```
2211 </div>
2212 
2213 An example XML instance of `ns__record` is:
2214 
2215 <div class="alt">
2216 ```xml
2217 <ns:record xmlns:ns="urn:types" full-name="Joe" tax-id="1234567890">
2218  <married-to full-name="Jane" tax-id="1987654320">
2219  </married-to>
2220 </ns:record>
2221 ```
2222 </div>
2223 
2224 A backtick XML tag name may contain any non-empty sequence of ASCII and UTF-8
2225 characters except white space and the backtick character. A backtick tag can
2226 be combined with member constraints and default member initializers:
2227 
2228  @uint64_t SSN `tax-id` 0:1 = 999;
2229 
2230 🔝 [Back to table of contents](#)
2231 
2232 ### Qualified and unqualified members {#toxsd9-6}
2233 
2234 Class, struct, and union data members are mapped to namespace qualified or
2235 unqualified tag names of local elements and attributes. If a data member has
2236 no prefix then the default form of qualification is applied based on the
2237 element/attribute form that is declared with the schema of the class, struct,
2238 or union type. If the member name has a namespace prefix by colon notation,
2239 then the prefix overrules the default (un)qualified form. Therefore,
2240 [colon notation](#toxsd2) is an effective mechanism to control qualification of
2241 tag names of individual members of classes, structs, and unions.
2242 
2243 The XML schema elementFormDefault and attributeFormDefault declarations control
2244 the tag name qualification of local elements and attributes, respectively.
2245 
2246 - "unqualified" indicates that local elements/attributes are not qualified with
2247  the namespace prefix.
2248 
2249 - "qualified" indicates that local elements/attributes must be qualified with
2250  the namespace prefix.
2251 
2252 Individual schema declarations of local elements and attributes may overrule
2253 this by using the form declaration in a schema and by using colon notation to
2254 add namespace prefixes to class, struct, and union members in the header file
2255 for soapcpp2.
2256 
2257 Consider for example an `ns__record` class in the `ns` namespace in which local
2258 elements are qualified and local attributes are unqualified by default:
2259 
2260 ```cpp
2261 //gsoap ns schema namespace: urn:types
2262 //gsoap ns schema elementForm: qualified
2263 //gsoap ns schema attributeForm: unqualified
2264 class ns__record
2265 {
2266  public:
2267  @std::string name;
2268  @uint64_t SSN;
2269  ns__record *spouse;
2270 };
2271 ```
2272 
2273 This class maps to a complexType in the soapcpp2-generated schema with
2274 targetNamespace "urn:types", elementFormDefault qualified and
2275 attributeFormDefault unqualified:
2276 
2277 <div class="alt">
2278 ```xml
2279 <schema targetNamespace="urn:types"
2280  ...
2281  elementFormDefault="qualified"
2282  attributeFormDefault="unqualified"
2283  ... >
2284  <complexType name="record">
2285  <sequence>
2286  <element name="spouse" type="ns:record" minOccurs="0" maxOccurs="1" nillable="true"/>
2287  </sequence>
2288  <attribute name="name" type="xsd:string" use="required"/>
2289  <attribute name="SSN" type="xsd:unsignedLong" use="required"/>
2290  </complexType>
2291 </schema>
2292 ```
2293 </div>
2294 
2295 An example XML instance of `ns__record` is:
2296 
2297 <div class="alt">
2298 ```xml
2299 <ns:record xmlns:ns="urn:types" name="Joe" SSN="1234567890">
2300  <ns:spouse> name="Jane" SSN="1987654320">
2301  </ns:spouse>
2302 </ns:record>
2303 ```
2304 </div>
2305 
2306 Note that the root element ns:record is qualified because it is a root element
2307 of the schema with target namespace "urn:types". Its local element ns:spouse
2308 is namespace qualified because the elementFormDefault of local elements is
2309 qualified. Attributes are unqualified.
2310 
2311 The default namespace (un)qualification of local elements and attributes can be
2312 overruled by adding a prefix to the member name by using colon notation:
2313 
2314 ```cpp
2315 //gsoap ns schema namespace: urn:types
2316 //gsoap ns schema elementForm: qualified
2317 //gsoap ns schema attributeForm: unqualified
2318 class ns__record
2319 {
2320  public:
2321  @std::string ns:name; // 'ns:' qualified
2322  @uint64_t SSN;
2323  ns__record *:spouse; // ':' unqualified (empty prefix)
2324 };
2325 ```
2326 
2327 The colon notation for member `ns:name` forces qualification of its attribute
2328 tag in XML. The colon notation for member `:spouse` removes qualification from
2329 its local element tag:
2330 
2331 <div class="alt">
2332 ```xml
2333 <schema targetNamespace="urn:types"
2334  ...
2335  elementFormDefault="unqualified"
2336  attributeFormDefault="unqualified"
2337  ... >
2338  <complexType name="record">
2339  <sequence>
2340  <element name="spouse" type="ns:record" minOccurs="0" maxOccurs="1" nillable="true" form="unqualified"/>
2341  </sequence>
2342  <attribute name="name" type="xsd:string" use="required" form="qualified"/>
2343  <attribute name="SSN" type="xsd:unsignedLong" use="required"/>
2344  </complexType>
2345 </schema>
2346 ```
2347 </div>
2348 
2349 XML instances of `ns__record` have unqualified spouse elements and qualified
2350 ns:name attributes:
2351 
2352 <div class="alt">
2353 ```xml
2354 <ns:record xmlns:ns="urn:types" ns:name="Joe" SSN="1234567890">
2355  <spouse> ns:name="Jane" SSN="1987654320">
2356  </spouse>
2357 </ns:record>
2358 ```
2359 </div>
2360 
2361 Note that data members can also be prefixed using the `prefix__name`
2362 convention. However, this has a different effect by referring to global (root)
2363 elements and attributes, see [document root element definitions](#toxsd9-7).
2364 
2365 [Backtick tag names](#toxsd9-5) can be used in place of the member name
2366 annotations and will achieve the same effect as described when these tag names
2367 are (un)qualified (requires gSOAP 2.8.30 and later versions).
2368 
2369 @note You must declare a target namespace with a `//gsoap ns schema namespace:`
2370 directive to enable the `elementForm` and `attributeForm` directives in order
2371 to generate valid schemas with soapcpp2. See [directives](#directives) for
2372 more details.
2373 
2374 🔝 [Back to table of contents](#)
2375 
2376 ### Defining document root elements {#toxsd9-7}
2377 
2378 To define and reference XML document root elements we use type names that start
2379 with an underscore:
2380 
2381 ```cpp
2382 class _ns__record
2383 ```
2384 
2385 Alternatively, we can use a typedef to define a document root element with a
2386 given type:
2387 
2388 ```cpp
2389 typedef ns__record _ns__record;
2390 ```
2391 
2392 This typedef maps to a global root element that is added to the
2393 soapcpp2-generated schema:
2394 
2395 <div class="alt">
2396 ```xml
2397 <element name="record" type="ns:record"/>
2398 ```
2399 </div>
2400 
2401 An example XML instance of `_ns__record` is:
2402 
2403 <div class="alt">
2404 ```xml
2405 <ns:record xmlns:ns="urn:types">
2406  <name>Joe</name>
2407  <SSN>1234567890</SSN>
2408  <spouse>
2409  <name>Jane</name>
2410  <SSN>1987654320</SSN>
2411  </spouse>
2412 </ns:record>
2413 ```
2414 </div>
2415 
2416 Global-level element/attribute definitions are also referenced and/or added to
2417 the generated schema when serializable data members reference these by their
2418 qualified name:
2419 
2420 ```cpp
2421 typedef std::string _ns__name 1 : 100;
2422 class _ns__record
2423 {
2424  public:
2425  @_QName xsi__type; // built-in XSD attribute xsi:type
2426  _ns__name ns__name; // ref to global ns:name element
2427  uint64_t SSN;
2428  _ns__record *spouse;
2429 };
2430 ```
2431 
2432 These types map to the following comonents in the soapcpp2-generated schema:
2433 
2434 <div class="alt">
2435 ```xml
2436 <simpleType name="name">
2437  <restriction base="xsd:string">
2438  <minLength value="1"/>
2439  <maxLength value="100"/>
2440  </restriction>
2441 </simpleType>
2442 <element name="name" type="ns:name"/>
2443 <complexType name="record">
2444  <sequence>
2445  <element ref="ns:name" minOccurs="1" maxOccurs="1"/>
2446  <element name="SSN" type="xsd:unsignedLong" minOccurs="1" maxOccurs="1"/>
2447  <element name="spouse" type="ns:record" minOccurs="0" maxOccurs="1" nillable="true"/>
2448  </sequence>
2449  <attribute ref="xsi:type" use="optional"/>
2450 </complexType>
2451 <element name="record" type="ns:record"/>
2452 ```
2453 </div>
2454 
2455 Use only use qualified member names when their types match the global-level
2456 element types that they refer to. For example:
2457 
2458 ```cpp
2459 typedef std::string _ns__name; // global element ns:name of type xsd:string
2460 class _ns__record
2461 {
2462  public:
2463  int ns__name; // BAD: global element ns:name is NOT type int
2464  _ns__record ns__record; // OK: ns:record is a global-level root element
2465  ...
2466 };
2467 ```
2468 
2469 Therefore, we recommend to use qualified member names only when necessary to
2470 refer to standard XSD elements and attributes, such as `xsi__type`, and
2471 `xsd__lang`.
2472 
2473 By contrast, colon notation has the desired effect to (un)qualify local tag
2474 names by overruling the default element/attribute namespace qualification, see
2475 [qualified and unqualified members](#toxsd9-6).
2476 
2477 As an alternative to prefixing member names, use the backtick tag (requires
2478 gSOAP 2.8.30 and later versions):
2479 
2480 ```cpp
2481 typedef std::string _ns__name 1 : 100;
2482 class _ns__record
2483 {
2484  public:
2485  @_QName t `xsi:type`; // built-in XSD attribute xsi:type
2486  _ns__name s `ns:name`; // ref to global ns:name element
2487  uint64_t SSN;
2488  _ns__record *spouse;
2489 };
2490 ```
2491 
2492 🔝 [Back to table of contents](#)
2493 
2494 ### (Smart) pointer members and their occurrence constraints {#toxsd9-8}
2495 
2496 A public pointer-typed data member is serialized by following its (smart)
2497 pointer(s) to the value pointed to. To serialize pointers to dynamic arrays of
2498 data, please see the next section on
2499 [container and array members and their occurrence constraints](#toxsd9-9).
2500 
2501 Pointers that are NULL and smart pointers that are empty are serialized to
2502 produce omitted element and attribute values, unless an element is required
2503 and is nillable.
2504 
2505 To control the occurrence requirements of pointer-based data members,
2506 occurrence constraints are associated with data members in the form of a range
2507 `minOccurs : maxOccurs`. For non-repeatable (meaning, not a container or array)
2508 data members, there are only three reasonable occurrence constraints:
2509 
2510 - `0:0` means that this element or attribute is prohibited.
2511 - `0:1` means that this element or attribute is optional.
2512 - `1:1` means that this element or attribute is required.
2513 
2514 Pointer-based data members have a default `0:1` occurrence constraint, making
2515 them optional, and their XML schema local element/attribute definition is
2516 marked as nillable. Non-pointer data members have a default `1:1` occurence
2517 constraint, making them required.
2518 
2519 A `nullptr` occurrence constraint may be applicable to required elements that
2520 are nillable pointer types, thus `nullptr 1:1`. This indicates that the
2521 element is nillable (can be `NULL` or `nullptr`). A pointer data member that
2522 is explicitly marked as required and nillable with `nullptr 1:1` will be
2523 serialized as an element with an `xsi:nil` attribute, thus effectively
2524 revealing the NULL property of its value.
2525 
2526 A non-pointer data member that is explicitly marked as optional with `0:1` will
2527 be set to its default value when no XML value is presented to the deserializer.
2528 A default value can be assigned to a data member that has a primitive type or
2529 is a (smart) pointer to primitive type.
2530 
2531 Consider for example:
2532 
2533 ```cpp
2534 class ns__record
2535 {
2536  public:
2537  std::shared_ptr<std::string> name; // optional (0:1)
2538  uint64_t SSN 0:1 = 999; // forced this to be optional with default 999
2539  ns__record *spouse 1:1; // forced this to be required (only married people)
2540 };
2541 ```
2542 
2543 This class maps to a complexType in the soapcpp2-generated schema:
2544 
2545 <div class="alt">
2546 ```xml
2547 <complexType name="record">
2548  <sequence>
2549  <element name="name" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
2550  <element name="SSN" type="xsd:unsignedLong" minOccurs="0" maxOccurs="1" default="999"/>
2551  <element name="spouse" type="ns:record" minOccurs="1" maxOccurs="1" nillable="true"/>
2552  </sequence>
2553 </complexType>
2554 ```
2555 </div>
2556 
2557 An example XML instance of `ns__record` with its `name` string value set to
2558 `Joe`, `SSN` set to its default, and `spouse` set to NULL:
2559 
2560 <div class="alt">
2561 ```xml
2562 <ns:record xmlns:ns="urn:types" ...>
2563  <name>Joe</name>
2564  <SSN>999</SSN>
2565  <spouse xsi:nil="true"/>
2566 </ns:record>
2567 ```
2568 </div>
2569 
2570 @note In general, a smart pointer is simply declared as a `volatile` template
2571 in a gSOAP header file for soapcpp2:
2572 
2573 ```cpp
2574 volatile template <class T> class NAMESPACE::shared_ptr;
2575 ```
2576 
2577 @note The soapcpp2 tool generates code that uses `NAMESPACE::shared_ptr` and
2578 `NAMESPACE::make_shared` to create shared pointers to objects, where
2579 `NAMESPACE` is any valid C++ namespace such as `std` and `boost` if you have
2580 Boost installed.
2581 
2582 🔝 [Back to table of contents](#)
2583 
2584 ### Container and array members and their occurrence constraints {#toxsd9-9}
2585 
2586 Class and struct data member types that are containers `std::deque`,
2587 `std::list`, `std::vector` and `std::set` are serialized as a collection of
2588 the values they contain. You can also serialize dynamic arrays, which is the
2589 alternative for C to store collections of data. Let's start with STL containers.
2590 
2591 You can use `std::deque`, `std::list`, `std::vector`, and `std::set` containers
2592 by importing:
2593 
2594 ```cpp
2595 #import "import/stl.h" // import all containers
2596 #import "import/stldeque.h" // import deque
2597 #import "import/stllist.h" // import list
2598 #import "import/stlvector.h" // import vector
2599 #import "import/stlset.h" // import set
2600 ```
2601 
2602 For example, to use a vector data mamber to store names in a record:
2603 
2604 ```cpp
2605 #import "import/stlvector.h"
2606 class ns__record
2607 {
2608  public:
2609  std::vector<std::string> names;
2610  uint64_t SSN;
2611 };
2612 ```
2613 
2614 To limit the number of names in the vector within reasonable bounds, occurrence
2615 constraints are associated with the container. Occurrence constraints are of
2616 the form `minOccurs : maxOccurs`:
2617 
2618 ```cpp
2619 #import "import/stlvector.h"
2620 class ns__record
2621 {
2622  public:
2623  std::vector<std::string> names 1:10;
2624  uint64_t SSN;
2625 };
2626 ```
2627 
2628 This class maps to a complexType in the soapcpp2-generated schema:
2629 
2630 <div class="alt">
2631 ```xml
2632 <complexType name="record">
2633  <sequence>
2634  <element name="name" type="xsd:string" minOccurs="1" maxOccurs="10"/>
2635  <element name="SSN" type="xsd:unsignedLong" minOccurs="1" maxOccurs="1""/>
2636  </sequence>
2637 </complexType>
2638 ```
2639 </div>
2640 
2641 @note In general, a container is simply declared as a template in a gSOAP
2642 header file for soapcpp2. All class templates are considered containers
2643 (except when declared `volatile`, see smart pointers). For example,
2644 `std::vector` is declared in `gsoap/import/stlvector.h` as:
2645 
2646 ```cpp
2647 template <class T> class std::vector;
2648 ```
2649 
2650 @note You can define and use your own containers. The soapcpp2 tool generates
2651 code that uses the following members of the `template <typename T> class C`
2652 container:
2653 
2654 ```cpp
2655 void C::clear()
2656 C::iterator C::begin()
2657 C::const_iterator C::begin() const
2658 C::iterator C::end()
2659 C::const_iterator C::end() const
2660 size_t C::size() const
2661 C::iterator C::insert(C::iterator pos, const T& val)
2662 ```
2663 
2664 @note For more details see the example `simple_vector` container with
2665 documentation in the package under `gsoap/samples/template`.
2666 
2667 Because C does not support a container template library, we can use a
2668 dynamically-sized array of values. This array is declared as a size-pointer
2669 pair of members within a struct or class. The array size information is stored
2670 in a special size tag member with the name `__size` or `__sizeX`, where `X` can
2671 be any name, or by an `$int` member to identify the member as a special size
2672 tag:
2673 
2674 ```cpp
2675 struct ns__record
2676 {
2677  $int sizeofnames; // array size
2678  char* *names; // array of char* names
2679  uint64_t SSN;
2680 };
2681 ```
2682 
2683 This class maps to a complexType in the soapcpp2-generated schema:
2684 
2685 <div class="alt">
2686 ```xml
2687 <complexType name="record">
2688  <sequence>
2689  <element name="name" type="xsd:string" minOccurs="0" maxOccurs="unbounded" nillable="true"/>
2690  <element name="SSN" type="xsd:unsignedLong" minOccurs="1" maxOccurs="1""/>
2691  </sequence>
2692 </complexType>
2693 ```
2694 </div>
2695 
2696 To limit the number of names in the array within reasonable bounds, occurrence
2697 constraints are associated with the array size member. Occurrence constraints
2698 are of the form `minOccurs : maxOccurs`:
2699 
2700 ```cpp
2701 struct ns__record
2702 {
2703  $int sizeofnames 1:10; // array size 1..10
2704  char* *names; // array of one to ten char* names
2705  uint64_t SSN;
2706 };
2707 ```
2708 
2709 This class maps to a complexType in the soapcpp2-generated schema:
2710 
2711 <div class="alt">
2712 ```xml
2713 <complexType name="record">
2714  <sequence>
2715  <element name="name" type="xsd:string" minOccurs="1" maxOccurs="10" nillable="true"/>
2716  <element name="SSN" type="xsd:unsignedLong" minOccurs="1" maxOccurs="1""/>
2717  </sequence>
2718 </complexType>
2719 ```
2720 </div>
2721 
2722 🔝 [Back to table of contents](#)
2723 
2724 ### Tagged union members {#toxsd9-10}
2725 
2726 A union member in a class or in a struct cannot be serialized unless a
2727 discriminating *variant selector* member is provided that tells the serializer
2728 which union field to serialize. This effectively creates a *tagged union*.
2729 
2730 The variant selector is associated with the union as a selector-union pair of members.
2731 The variant selector is a member with the name `__union` or `__unionX`, where
2732 `X` can be any name, or by an `$int` member to identify the member as a variant
2733 selector tag:
2734 
2735 ```cpp
2736 class ns__record
2737 {
2738  public:
2739  $int xORnORs; // variant selector with values SOAP_UNION_fieldname
2740  union choice
2741  {
2742  float x;
2743  int n;
2744  char *s;
2745  } u;
2746  std::string name;
2747 };
2748 ```
2749 
2750 The variant selector values are auto-generated based on the union name `choice`
2751 and the names of its members `x`, `n`, and `s`:
2752 
2753 - `xORnORs = SOAP_UNION_choice_x` when `u.x` is valid.
2754 - `xORnORs = SOAP_UNION_choice_n` when `u.n` is valid.
2755 - `xORnORs = SOAP_UNION_choice_s` when `u.s` is valid.
2756 - `xORnORs = 0` when none are valid (should only be used with great care,
2757  because XSD validation may fail when content is required but absent).
2758 
2759 This class maps to a complexType with a sequence and choice in the
2760 soapcpp2-generated schema:
2761 
2762 <div class="alt">
2763 ```xml
2764 <complexType name="record">
2765  <sequence>
2766  <choice>
2767  <element name="x" type="xsd:float" minOccurs="1" maxOccurs="1"/>
2768  <element name="n" type="xsd:int" minOccurs="1" maxOccurs="1"/>
2769  <element name="s" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
2770  </choice>
2771  <element name="names" type="xsd:string" minOccurs="1" maxOccurs="1" nillable="true"/>
2772  </sequence>
2773 </complexType>
2774 ```
2775 </div>
2776 
2777 An STL container or dynamic array of a union requires wrapping the variant
2778 selector and union member in a struct:
2779 
2780 ```cpp
2781 class ns__record
2782 {
2783  public:
2784  std::vector<
2785  struct ns__data // data with a choice of x, n, or s
2786  {
2787  $int xORnORs; // variant selector with values SOAP_UNION_fieldname
2788  union choice
2789  {
2790  float x;
2791  int n;
2792  char *s;
2793  } u;
2794  }> data; // vector with data
2795 };
2796 ```
2797 
2798 and an equivalent definition with a dynamic array instead of a `std::vector`
2799 (you can use this in C with structs):
2800 
2801 ```cpp
2802 class ns__record
2803 {
2804  public:
2805  $int sizeOfdata; // size of dynamic array
2806  struct ns__data // data with a choice of x, n, or s
2807  {
2808  $int xORnORs; // variant selector with values SOAP_UNION_fieldname
2809  union choice
2810  {
2811  float x;
2812  int n;
2813  char *s;
2814  } u;
2815  } *data; // points to the data array of length sizeOfdata
2816 };
2817 ```
2818 
2819 This maps to two complexTypes in the soapcpp2-generated schema:
2820 
2821 <div class="alt">
2822 ```xml
2823 <complexType name="data">
2824  <choice>
2825  <element name="x" type="xsd:float" minOccurs="1" maxOccurs="1"/>
2826  <element name="n" type="xsd:int" minOccurs="1" maxOccurs="1"/>
2827  <element name="s" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
2828  </choice>
2829 </complexType>
2830 <complexType name="record">
2831  <sequence>
2832  <element name="data" type="ns:data" minOccurs="0" maxOccurs="unbounded"/>
2833  </sequence>
2834 </complexType>
2835 ```
2836 </div>
2837 
2838 The XML value space consists of a sequence of item elements each wrapped in an
2839 data element:
2840 
2841 <div class="alt">
2842 ```xml
2843 <ns:record xmlns:ns="urn:types" ...>
2844  <data>
2845  <n>123</n>
2846  </data>
2847  <data>
2848  <x>3.1</x>
2849  </data>
2850  <data>
2851  <s>hello</s>
2852  </data>
2853  <data>
2854  <s>world</s>
2855  </data>
2856 </ns:record>
2857 ```
2858 </div>
2859 
2860 To remove the wrapping data element, simply rename the wrapping struct and
2861 member to `__data` to make this member invisible to the serializer with the
2862 double underscore prefix naming convention. Also use a dynamic array instead
2863 of a STL container (you can use this in C with structs):
2864 
2865 ```cpp
2866 class ns__record
2867 {
2868  public:
2869  $int sizeOfdata; // size of dynamic array
2870  struct __data // contains choice of x, n, or s
2871  {
2872  $int xORnORs; // variant selector with values SOAP_UNION_fieldname
2873  union choice
2874  {
2875  float x;
2876  int n;
2877  char *s;
2878  } u;
2879  } *__data; // points to the data array of length sizeOfdata
2880 };
2881 ```
2882 
2883 This maps to a complexType in the soapcpp2-generated schema:
2884 
2885 <div class="alt">
2886 ```xml
2887 <complexType name="record">
2888  <sequence minOccurs="0" maxOccurs="unbounded">
2889  <choice>
2890  <element name="x" type="xsd:float" minOccurs="1" maxOccurs="1"/>
2891  <element name="n" type="xsd:int" minOccurs="1" maxOccurs="1"/>
2892  <element name="s" type="xsd:string" minOccurs="0" maxOccurs="1" nillable="true"/>
2893  </choice>
2894  </sequence>
2895 </complexType>
2896 ```
2897 </div>
2898 
2899 The XML value space consists of a sequence of `<x>`, `<n>`, and/or `<s>`
2900 elements:
2901 
2902 <div class="alt">
2903 ```xml
2904 <ns:record xmlns:ns="urn:types" ...>
2905  <n>123</n>
2906  <x>3.1</x>
2907  <s>hello</s>
2908  <s>world</s>
2909 </ns:record>
2910 ```
2911 </div>
2912 
2913 Please note that structs, classes, and unions are unnested by soapcpp2 (as in
2914 the C standard of nested structs and unions). Therefore, the `choice` union in
2915 the `ns__record` class is redeclared at the top level despite its nesting
2916 within the `ns__record` class. This means that you will have to choose a
2917 unique name for each nested struct, class, and union.
2918 
2919 🔝 [Back to table of contents](#)
2920 
2921 ### Tagged void pointer members {#toxsd9-11}
2922 
2923 To serialize data pointed to by `void*` requires run-time type information that
2924 tells the serializer what type of data to serialize by means of a *tagged void
2925 pointer*. This type information is stored in a special type tag member of a
2926 struct/class with the name `__type` or `__typeX`, where `X` can be any name, or
2927 alternatively by an `$int` special member of any name as a type tag:
2928 
2929 ```cpp
2930 class ns__record
2931 {
2932  public:
2933  $int typeOfdata; // type tag with values SOAP_TYPE_T
2934  void *data; // points to some data of type T
2935 };
2936 ```
2937 
2938 A type tag member has nonzero values `SOAP_TYPE_T` where `T` is the name of a
2939 struct/class or the name of a primitive type, such as `int`, `std__string` (for
2940 `std::string`), `string` (for `char*`).
2941 
2942 This class maps to a complexType with a sequence in the soapcpp2-generated
2943 schema:
2944 
2945 <div class="alt">
2946 ```xml
2947 <complexType name="record">
2948  <sequence>
2949  <element name="data" type="xsd:anyType" minOccurs="0" maxOccurs="1"/>
2950  </sequence>
2951 </complexType>
2952 ```
2953 </div>
2954 
2955 The XML value space consists of the XML value space of the type with the
2956 addition of an `xsi:type` attribute to the enveloping element:
2957 
2958 <div class="alt">
2959 ```xml
2960 <ns:record xmlns:ns="urn:types" ...>
2961  <data xsi:type="xsd:int">123</data>
2962 </ns:record>
2963 ```
2964 </div>
2965 
2966 This `xsi:type` attribute is important for the receiving end to distinguish
2967 the type of data to instantiate. The receiver cannot deserialize the data
2968 without an `xsd:type` attribute.
2969 
2970 You can find the `SOAP_TYPE_T` name of each serializable type in the
2971 auto-generated soapStub.h file.
2972 
2973 Also all serializable C++ classes have a virtual `int T::soap_type()` member
2974 that returns their `SOAP_TYPE_T` value that you can use.
2975 
2976 When the `void*` pointer is NULL or when `typeOfdata` is zero, the data is not
2977 serialized.
2978 
2979 An STL container or dynamic array of `void*` pointers to `xsd:anyType` data
2980 requires wrapping the type tag and `void*` members in a struct:
2981 
2982 ```cpp
2983 class ns__record
2984 {
2985  public:
2986  std::vector<
2987  struct ns__data // data with an xsd:anyType item
2988  {
2989  $int typeOfitem; // type tag with values SOAP_TYPE_T
2990  void *item; // points to some item of type T
2991  }> data; // vector with data
2992 };
2993 ```
2994 
2995 and an equivalent definition with a dynamic array instead of a `std::vector`
2996 (you can use this in C with structs):
2997 
2998 ```cpp
2999 class ns__record
3000 {
3001  public:
3002  $int sizeOfdata; // size of dynamic array
3003  struct ns__data // data with an xsd:anyType item
3004  {
3005  $int typeOfitem; // type tag with values SOAP_TYPE_T
3006  void *item; // points to some item of type T
3007  } *data; // points to the data array of length sizeOfdata
3008 };
3009 ```
3010 
3011 This maps to two complexTypes in the soapcpp2-generated schema:
3012 
3013 <div class="alt">
3014 ```xml
3015 <complexType name="data">
3016  <sequence>
3017  <element name="item" type="xsd:anyType" minOccurs="1" maxOccurs="1" nillable="true"/>
3018  </sequence>
3019 </complexType>
3020 <complexType name="record">
3021  <sequence>
3022  <element name="data" type="ns:data" minOccurs="0" maxOccurs="unbounded"/>
3023  </sequence>
3024 </complexType>
3025 ```
3026 </div>
3027 
3028 The XML value space consists of a sequence of item elements each wrapped in a
3029 data element:
3030 
3031 <div class="alt">
3032 ```xml
3033 <ns:record xmlns:ns="urn:types" ...>
3034  <data>
3035  <item xsi:type="xsd:int">123</item>
3036  </data>
3037  <data>
3038  <item xsi:type="xsd:double">3.1</item>
3039  </data>
3040  <data>
3041  <item xsi:type="xsd:string">abc</item>
3042  </data>
3043 </ns:record>
3044 ```
3045 </div>
3046 
3047 To remove the wrapping data elements, simply rename the wrapping struct and
3048 member to `__data` to make this member invisible to the serializer with the
3049 double underscore prefix naming convention. Also use a dynamic array instead
3050 of a STL container (you can use this in C with structs):
3051 
3052 ```cpp
3053 class ns__record
3054 {
3055  public:
3056  $int sizeOfdata; // size of dynamic array
3057  struct __data // contains xsd:anyType item
3058  {
3059  $int typeOfitem; // type tag with values SOAP_TYPE_T
3060  void *item; // points to some item of type T
3061  } *__data; // points to the data array of length sizeOfdata
3062 };
3063 ```
3064 
3065 This maps to a complexType in the soapcpp2-generated schema:
3066 
3067 <div class="alt">
3068 ```xml
3069 <complexType name="record">
3070  <sequence minOccurs="0" maxOccurs="unbounded">
3071  <element name="item" type="xsd:anyType" minOccurs="1" maxOccurs="1"/>
3072  </sequence>
3073 </complexType>
3074 ```
3075 </div>
3076 
3077 The XML value space consists of a sequence of data elements:
3078 
3079 <div class="alt">
3080 ```xml
3081 <ns:record xmlns:ns="urn:types" ...>
3082  <item xsi:type="xsd:int">123</item>
3083  <item xsi:type="xsd:double">3.1</item>
3084  <item xsi:type="xsd:string">abc</item>
3085 </ns:record>
3086 ```
3087 </div>
3088 
3089 Again, please note that structs, classes, and unions are unnested by soapcpp2
3090 (as in the C standard of nested structs and unions). Therefore, the `__data`
3091 struct in the `ns__record` class is redeclared at the top level despite its
3092 nesting within the `ns__record` class. This means that you will have to choose
3093 a unique name for each nested struct, class, and union.
3094 
3095 @see Section [XSD type bindings](#typemap2).
3096 
3097 🔝 [Back to table of contents](#)
3098 
3099 ### Adding get and set methods {#toxsd9-12}
3100 
3101 A public `get` method may be added to a class or struct, which will be
3102 triggered by the deserializer. This method will be invoked right after the
3103 instance is populated by the deserializer. The `get` method can be used to
3104 update or verify deserialized content. It should return `SOAP_OK` or set
3105 `soap::error` to a nonzero error code and return it.
3106 
3107 A public `set` method may be added to a class or struct, which will be
3108 triggered by the serializer. The method will be invoked just before the
3109 instance is serialized. Likewise, the `set` method should return `SOAP_OK` or
3110 set set `soap::error` to a nonzero error code and return it.
3111 
3112 For example, adding a `set` and `get` method to a class declaration:
3113 
3114 ```cpp
3115 class ns__record
3116 {
3117  public:
3118  int set(struct soap*); // triggered before serialization
3119  int get(struct soap*); // triggered after deserialization
3120  ...
3121 };
3122 ```
3123 
3124 To add these and othe rmethods to classes and structs with wsdl2h and
3125 `typemap.dat`, please see [class/struct member additions](#typemap3).
3126 
3127 🔝 [Back to table of contents](#)
3128 
3129 ### Operations on classes and structs {#toxsd9-13}
3130 
3131 The following functions/macros are generated by soapcpp2 for each type `T`,
3132 which should make it easier to send, receive, and copy XML data in C and in
3133 C++:
3134 
3135 - `int soap_write_T(struct soap*, T*)` writes an instance of `T` to a file via
3136  file descriptor `int soap::sendfd)` or to a stream via `std::ostream
3137  *soap::os` (C++ only) or saves into a NUL-terminated string by setting
3138  `const char **soap::os` to a string pointer to be set (C only). Returns
3139  `SOAP_OK` on success or an error code, also stored in `soap->error`.
3140 
3141 - `int soap_read_T(struct soap*, T*)` reads an instance of `T` from a file via
3142  file descriptor `int soap::recvfd)` or from a stream via `std::istream
3143  *soap::is` (C++ only) or reads from a NUL-termianted string `const char
3144  *soap::is` (C only). Returns `SOAP_OK` on success or an error code, also
3145  stored in `soap->error`.
3146 
3147 - `void soap_default_T(struct soap*, T*)` sets an instance `T` to its default
3148  value, resetting members of a struct to their initial values (for classes we
3149  use method `T::soap_default`, see below).
3150 
3151 - `T * soap_dup_T(struct soap*, T *dst, const T *src)` (soapcpp2 option `-Ec`)
3152  deep copy `src` into `dst`, replicating all deep cycles and shared pointers
3153  when a managing soap context is provided as argument. When `dst` is NULL,
3154  allocates space for `dst`. Deep copy is a tree when argument is NULL, but the
3155  presence of deep cycles will lead to non-termination. Use flag
3156  `SOAP_XML_TREE` with managing context to copy into a tree without cycles and
3157  pointers to shared objects. Returns `dst` (or allocated space when `dst` is
3158  NULL).
3159 
3160 - `void soap_del_T(const T*)` (soapcpp2 option `-Ed`) deletes all
3161  heap-allocated members of this object by deep deletion ONLY IF this object
3162  and all of its (deep) members are not managed by a soap context AND the deep
3163  structure is a tree (no cycles and co-referenced objects by way of multiple
3164  (non-smart) pointers pointing to the same data). Can be safely used after
3165  `soap_dup(NULL)` to delete the deep copy. Does not delete the object itself.
3166 
3167 When in C++ mode, soapcpp2 tool adds several methods to classes in addition to
3168 adding a default constructor and destructor (when these were not explicitly
3169 declared).
3170 
3171 The public methods added to a class `T`:
3172 
3173 - `virtual int T::soap_type(void)` returns a unique type ID (`SOAP_TYPE_T`).
3174  This numeric ID can be used to distinguish base from derived instances.
3175 
3176 - `virtual void T::soap_default(struct soap*)` sets all data members to
3177  default values.
3178 
3179 - `virtual void T::soap_serialize(struct soap*) const` serializes object to
3180  prepare for SOAP 1.1/1.2 encoded output (or with `SOAP_XML_GRAPH`) by
3181  analyzing its (cyclic) structures.
3182 
3183 - `virtual int T::soap_put(struct soap*, const char *tag, const char *type) const`
3184  emits object in XML, compliant with SOAP 1.1 encoding style, return error
3185  code or `SOAP_OK`. Requires `soap_begin_send(soap)` and
3186  `soap_end_send(soap)`.
3187 
3188 - `virtual int T::soap_out(struct soap*, const char *tag, int id, const char *type) const`
3189  emits object in XML, with tag and optional id attribute and `xsi:type`,
3190  return error code or `SOAP_OK`. Requires `soap_begin_send(soap)` and
3191  `soap_end_send(soap)`.
3192 
3193 - `virtual void * T::soap_get(struct soap*, const char *tag, const char *type)`
3194  Get object from XML, compliant with SOAP 1.1 encoding style, return pointer
3195  to object or NULL on error. Requires `soap_begin_recv(soap)` and
3196  `soap_end_recv(soap)`.
3197 
3198 - `virtual void *soap_in(struct soap*, const char *tag, const char *type)`
3199  Get object from XML, with matching tag and type (NULL matches any tag and
3200  type), return pointer to object or NULL on error. Requires
3201  `soap_begin_recv(soap)` and `soap_end_recv(soap)`
3202 
3203 - `virtual T * T::soap_alloc(void) const` returns a new object of type `T`,
3204  default initialized and not managed by a soap context.
3205 
3206 - `virtual T * T::soap_dup(struct soap*) const` (soapcpp2 option `-Ec`) returns
3207  a duplicate of this object by deep copying, replicating all deep cycles and
3208  shared pointers when a managing soap context is provided as argument. Deep
3209  copy is a tree when argument is NULL, but the presence of deep cycles will
3210  lead to non-termination. Use flag `SOAP_XML_TREE` with the managing context
3211  to copy into a tree without cycles and pointers to shared objects.
3212 
3213 - `virtual void T::soap_del() const` (soapcpp2 option `-Ed`) deletes all
3214  heap-allocated members of this object by deep deletion ONLY IF this object
3215  and all of its (deep) members are not managed by a soap context AND the deep
3216  structure is a tree (no cycles and co-referenced objects by way of multiple
3217  (non-smart) pointers pointing to the same data). Can be safely used after
3218  `soap_dup(NULL)` to delete the deep copy. Does not delete the object itself.
3219 
3220 Also for C++, there are four variations of `soap_new_T` for
3221 class/struct/template type `T` that soapcpp2 auto-generates to create instances
3222 on a context-managed heap:
3223 
3224 - `T * soap_new_T(struct soap*)` returns a new instance of `T` with default data
3225  member initializations that are set with the soapcpp2 auto-generated `void
3226  T::soap_default(struct soap*)` method), but ONLY IF the soapcpp2
3227  auto-generated default constructor is used that invokes `soap_default()` and
3228  was not replaced by a user-defined default constructor.
3229 
3230 - `T * soap_new_T(struct soap*, int n)` returns an array of `n` new instances of
3231  `T`. Similar to the above, instances are initialized.
3232 
3233 - `T * soap_new_req_T(struct soap*, ...)` returns a new instance of `T` and sets
3234  the required data members to the values specified in `...`. The required data
3235  members are those with nonzero minOccurs, see the subsections on
3236  [(smart) pointer members and their occurrence constraints](#toxsd9-8) and
3237  [container and array members and their occurrence constraints](#toxsd9-9).
3238 
3239 - `T * soap_new_set_T(struct soap*, ...)` returns a new instance of `T` and sets
3240  the public/serializable data members to the values specified in `...`.
3241 
3242 The above functions can be invoked with a NULL `soap` context, but we will be
3243 responsible to use `delete T` to remove this instance from the unmanaged heap.
3244 
3245 🔝 [Back to table of contents](#)
3246 
3247 Special classes and structs {#toxsd10}
3248 ---------------------------
3249 
3250 ### SOAP encoded arrays {#toxsd10-1}
3251 
3252 A class or struct with the following layout is a one-dimensional SOAP encoded
3253 Array type:
3254 
3255 ```cpp
3256 class ArrayOfT
3257 {
3258  public:
3259  T *__ptr; // array pointer
3260  int __size; // array size
3261 };
3262 ```
3263 
3264 where `T` is the array element type. A multidimensional SOAP Array is:
3265 
3266 ```cpp
3267 class ArrayOfT
3268 {
3269  public:
3270  T *__ptr; // array pointer
3271  int __size[N]; // array size of each dimension
3272 };
3273 ```
3274 
3275 where `N` is the constant number of dimensions. The pointer points to an array
3276 of `__size[0]*__size[1]* ... * __size[N-1]` elements.
3277 
3278 This maps to a complexType restriction of SOAP-ENC:Array in the
3279 soapcpp2-generated schema:
3280 
3281 <div class="alt">
3282 ```xml
3283 <complexType name="ArrayOfT">
3284  <complexContent>
3285  <restriction base="SOAP-ENC:Array">
3286  <sequence>
3287  <element name="item" type="T" minOccurs="0" maxOccurs="unbounded" nillable="true"/>
3288  </sequence>
3289  <attribute ref="SOAP-ENC:arrayType" WSDL:arrayType="ArrayOfT[]"/>
3290  </restriction>
3291  </complexContent>
3292 </complexType>
3293 ```
3294 </div>
3295 
3296 The name of the class can be arbitrary. We often use `ArrayOfT` without a
3297 prefix to distinguish arrays from other classes and structs.
3298 
3299 With SOAP 1.1 encoding, an optional offset member can be added that controls
3300 the start of the index range for each dimension:
3301 
3302 ```cpp
3303 class ArrayOfT
3304 {
3305  public:
3306  T *__ptr; // array pointer
3307  int __size[N]; // array size of each dimension
3308  int __offset[N]; // array offsets to start each dimension
3309 };
3310 ```
3311 
3312 For example, we can define a matrix of floats as follows:
3313 
3314 ```cpp
3315 class Matrix
3316 {
3317  public:
3318  double *__ptr;
3319  int __size[2];
3320 };
3321 ```
3322 
3323 The following code populates the matrix and serializes it in XML:
3324 
3325 ```cpp
3326 soap *soap = soap_new1(SOAP_XML_INDENT);
3327 Matrix A;
3328 double a[6] = { 1, 2, 3, 4, 5, 6 };
3329 A.__ptr = a;
3330 A.__size[0] = 2;
3331 A.__size[1] = 3;
3332 soap_write_Matrix(soap, &A);
3333 ```
3334 
3335 Matrix A is serialized as an array with 2x3 values:
3336 
3337 <div class="alt">
3338 ```xml
3339 <SOAP-ENC:Array SOAP-ENC:arrayType="xsd:double[2,3]" ...>
3340  <item>1</item>
3341  <item>2</item>
3342  <item>3</item>
3343  <item>4</item>
3344  <item>5</item>
3345  <item>6</item>
3346 </SOAP-ENC:Array>
3347 ```
3348 </div>
3349 
3350 🔝 [Back to table of contents](#)
3351 
3352 ### XSD hexBinary and base64Binary types {#toxsd10-2}
3353 
3354 A special case of a one-dimensional array is used to define `xsd:hexBinary` and
3355 `xsd:base64Binary` types when the pointer type is `unsigned char`:
3356 
3357 ```cpp
3358 class xsd__hexBinary
3359 {
3360  public:
3361  unsigned char *__ptr; // points to raw binary data
3362  int __size; // size of data
3363 };
3364 ```
3365 
3366 and
3367 
3368 ```cpp
3369 class xsd__base64Binary
3370 {
3371  public:
3372  unsigned char *__ptr; // points to raw binary data
3373  int __size; // size of data
3374 };
3375 ```
3376 
3377 🔝 [Back to table of contents](#)
3378 
3379 ### MIME/MTOM attachment binary types {#toxsd10-3}
3380 
3381 A class or struct with a binary content layout can be extended to support
3382 MIME/MTOM (and older DIME) attachments, such as in xop:Include elements:
3383 
3384 ```cpp
3385 //gsoap xop schema import: http://www.w3.org/2004/08/xop/include
3386 class _xop__Include
3387 {
3388  public:
3389  unsigned char *__ptr; // points to raw binary data
3390  int __size; // size of data
3391  char *id; // NULL to generate an id, or set to a unique UUID
3392  char *type; // MIME type of the data
3393  char *options; // optional description of MIME attachment
3394 };
3395 ```
3396 
3397 Attachments are beyond the scope of this document. The `SOAP_ENC_MIME` and
3398 `SOAP_ENC_MTOM` context flag must be set to enable attachments. See the
3399 [gSOAP user guide](http://www.genivia.com/doc/soapdoc2.html) for more details.
3400 
3401 🔝 [Back to table of contents](#)
3402 
3403 ### Wrapper class/struct with simpleContent {#toxsd10-4}
3404 
3405 A class or struct with the following layout is a complexType that wraps
3406 simpleContent:
3407 
3408 ```cpp
3409 class ns__simple
3410 {
3411  public:
3412  T __item;
3413 };
3414 ```
3415 
3416 The type `T` is a primitive type (`bool`, `enum`, `time_t`, numeric and string
3417 types), `xsd__hexBinary`, `xsd__base64Binary`, and custom serializers, such as
3418 `xsd__dateTime`.
3419 
3420 This maps to a complexType with simpleContent in the soapcpp2-generated schema:
3421 
3422 <div class="alt">
3423 ```xml
3424 <complexType name="simple">
3425  <simpleContent>
3426  <extension base="T"/>
3427  </simpleContent>
3428 </complexType>
3429 ```
3430 </div>
3431 
3432 A wrapper class/struct may include any number of attributes declared with `@`.
3433 
3434 🔝 [Back to table of contents](#)
3435 
3436 ### DOM anyType and anyAttribute {#toxsd10-5}
3437 
3438 Use of a DOM is optional and enabled by `#import "dom.h"` to use the DOM
3439 `xsd__anyType` element node and `xsd__anyAttribute` attribute node:
3440 
3441 ```cpp
3442 #import "dom.h"
3443 
3444 class ns__record
3445 {
3446  public:
3447  @xsd__anyAttribute attributes; // list of DOM attributes
3448  ...
3449  xsd__anyType *name; // optional DOM element
3450 };
3451 ```
3452 
3453 where `name` contains XML stored in a DOM node set and `attributes` is a list
3454 of all visibly rendered attributes. The name `attributes` is arbitrary and any
3455 name will suffice.
3456 
3457 You should place the `xsd__anyType` members at the end of the struct or class.
3458 This ensures that the DOM members are populated last as a "catch all". A
3459 member name starting with double underscore is a wildcard member name and
3460 matches any XML tag. These members are placed at the end of a struct or class
3461 automatically by soapcpp2.
3462 
3463 An `#import "dom.h"` import is automatically added by wsdl2h with option `-d`
3464 to bind `xsd:anyType` to DOM nodes, and also to populate `xsd:any`,
3465 `xsd:anyAttribute` and `xsd:mixed` XML content:
3466 
3467 ```cpp
3468 #import "dom.h"
3469 
3470 class ns__record
3471 {
3472  public:
3473  ...
3474  @xsd__anyAttribute __anyAttribute; // optional DOM attributes
3475  std::vector<xsd__anyType> __any 0; // optional DOM elements
3476  xsd__anyType __mixed 0; // optional mixed content
3477 };
3478 ```
3479 
3480 where the members prefixed with `__` are "invisible" to the XML parser, meaning
3481 that these members are not bound to XML tag names.
3482 
3483 In C you can use a dynamic arrary instead of `std::vector`:
3484 
3485 ```cpp
3486 #import "dom.h"
3487 
3488 struct ns__record
3489 {
3490  ...
3491  @xsd__anyAttribute __anyAttribute; // optional DOM attributes
3492  $int __sizeOfany; // size of the array
3493  xsd__anyType *__any; // optional DOM elements
3494  xsd__anyType __mixed 0; // optional mixed content
3495 };
3496 ```
3497 
3498 Classes can inherit DOM, which enables full use of polymorphism with one base
3499 DOM class:
3500 
3501 ```cpp
3502 #import "dom.h"
3503 
3504 class ns__record : public xsd__anyType
3505 {
3506  ...
3507  std::vector<xsd__anyType*> array; // array of objects of any class
3508 };
3509 ```
3510 
3511 This permits an `xsd__anyType` pointer to refer to a derived class such as
3512 `ns__record`, which will be serialized with an `xsi:type` attribute that is
3513 set to "ns:record". The `xsi:type` attributes add the necessary type information
3514 to distinguish the XML content from the DOM base type. This is important for
3515 the receiving end: without `xsd:type` attributes with type names, only base DOM
3516 objects are recognized and instantiated.
3517 
3518 Because C lacks OOP principles such as class inheritance and polymorphism, you
3519 will need to use the special [`void*` members](#toxsd9-11) to serialize data
3520 pointed to by a `void*` member.
3521 
3522 To ensure that wsdl2h generates pointer-based `xsd__anyType` DOM nodes with
3523 option `-d` for `xsd:any`, add the following line to `typemap.dat`:
3524 
3525  xsd__any = | xsd__anyType*
3526 
3527 This lets wsdl2h produce class/struct members and containers with
3528 `xsd__anyType*` for `xsd:any` instead of `xsd__anyType`. To just force all
3529 `xsd:anyType` uses to be pointer-based, declare in `typemap.dat`:
3530 
3531  xsd__anyType = | xsd__anyType*
3532 
3533 If you use wsdl2h with option `-p` with option `-d` then every class will
3534 inherit DOM as shown above. Without option `-d`, an `xsd__anyType` type is
3535 generated to serve as the root type in the type hierarchy:
3536 
3537 ```cpp
3538 class xsd__anyType { _XML __item; struct soap *soap; };
3539 
3540 class ns__record : public xsd__anyType
3541 {
3542  ...
3543 };
3544 ```
3545 
3546 where the `_XML __item` member holds any XML content as a literal XML string.
3547 
3548 To use the DOM API, compile `dom.c` (or `dom.cpp` for C++), or link with
3549 `-lgsoapssl` (or `-lgsoapssl++` for C++).
3550 
3551 @see Documentation of [XML DOM and XPath](http://www.genivia.com/doc/dom/html)
3552 for more details.
3553 
3554 🔝 [Back to table of contents](#)
3555 
3556 Directives {#directives}
3557 ==========
3558 
3559 You can use `//gsoap` directives in the gSOAP header file with the data binding
3560 interface for soapcpp2. These directives are used to configure the code
3561 generated by soapcpp2 by declaring various. properties of Web services and XML
3562 schemas. When using the wsdl2h tool, you will notice that wsdl2h generates
3563 directives automatically based on the WSDL and XSD input.
3564 
3565 Service directives are applicable to service and operations described by WSDL.
3566 Schema directives are applicable to types, elements, and attributes defined by
3567 XML schemas.
3568 
3569 🔝 [Back to table of contents](#)
3570 
3571 Service directives {#directives-1}
3572 ------------------
3573 
3574 A service directive must start at a new line and is of the form:
3575 
3576 ```cpp
3577 //gsoap <prefix> service <property>: <value>
3578 ```
3579 
3580 where `<prefix>` is the XML namespace prefix of a service binding. The
3581 `<property>` and `<value>` fields are one of the following:
3582 
3583 property | value
3584 --------------- | -----
3585 `name` | name of the service, optionally followed by text describing the service
3586 `namespace` | URI of the WSDL targetNamespace
3587 `documentation` | text describing the service (see also the `name` property), multiple permitted
3588 `doc` | same as above, shorthand form
3589 `style` | `document` (default) SOAP messaging style or `rpc` for SOAP RPC
3590 `encoding` | `literal` (default), `encoded` for SOAP encoding, or a custom URI
3591 `protocol` | specifies SOAP or REST, see below
3592 `port` | URL of the service endpoint, usually an http or https address
3593 `transport` | URI declaration of the transport, usually `http://schemas.xmlsoap.org/soap/http`
3594 `definitions` | name of the WSDL definitions/\@name
3595 `type` | name of the WSDL definitions/portType/\@name (WSDL2.0 interface/\@name)
3596 `binding` | name of the WSDL definitions/binding/\@name
3597 `portName` | name of the WSDL definitions/service/port/\@name
3598 `portType` | an alias for the `type` property
3599 `interface` | an alias for the `type` property
3600 `location` | an alias for the `port` property
3601 `endpoint` | an alias for the `port` property
3602 
3603 The service `name` and `namespace` properties are required in order to generate
3604 a valid WSDL with soapcpp2. The other properties are optional.
3605 
3606 The `style` and `encoding` property defaults are changed with soapcpp2 option
3607 `-e` to `rpc` and `encoded`, respectively.
3608 
3609 The `protocol` property is `SOAP` by default (SOAP 1.1). Protocol property
3610 values are:
3611 
3612 protocol value | description
3613 -------------- | -----------
3614 `SOAP` | SOAP transport, supporting both SOAP 1.1 and 1.2
3615 `SOAP1.1` | SOAP 1.1 transport (same as soapcpp2 option `-1`)
3616 `SOAP1.2` | SOAP 1.2 transport (same as soapcpp2 option `-2`)
3617 `SOAP-GET` | one-way SOAP 1.1 or 1.2 with HTTP GET
3618 `SOAP1.1-GET` | one-way SOAP 1.1 with HTTP GET
3619 `SOAP1.2-GET` | one-way SOAP 1.2 with HTTP GET
3620 `HTTP` | non-SOAP REST protocol with HTTP POST
3621 `POST` | non-SOAP REST protocol with HTTP POST
3622 `GET` | non-SOAP REST protocol with HTTP GET
3623 `PUT` | non-SOAP REST protocol with HTTP PUT
3624 `DELETE` | non-SOAP REST protocol with HTTP DELETE
3625 
3626 You can bind service operations to the WSDL namespace of a service by using the
3627 namespace prefix as part of the identifier name of the function that defines
3628 the service operation:
3629 
3630 ```cpp
3631 int prefix__func(arg1, arg2, ..., argn, result);
3632 ```
3633 
3634 You can override the `port` endpoint URL at runtime in the auto-generated
3635 `soap_call_prefix__func` service call (C/C++ client side) and in the C++ proxy
3636 class service call.
3637 
3638 🔝 [Back to table of contents](#)
3639 
3640 Service method directives {#directives-2}
3641 -------------------------
3642 
3643 Service properties are applicable to a service and to all of its operations.
3644 Service method directives are specifically applicable to a service operation.
3645 
3646 A service method directive is of the form:
3647 
3648 ```cpp
3649 //gsoap <prefix> service method-<property>: <method> <value>
3650 ```
3651 
3652 where `<prefix>` is the XML namespace prefix of a service binding and
3653 `<method>` is the unqualified name of a service operation. The `<property>`
3654 and `<value>` fields are one of the following:
3655 
3656 method property | value
3657 --------------------------- | -----
3658 `method-documentation` | text describing the service operation
3659 `method` | same as above, shorthand form
3660 `method-action` | `""` or URI SOAPAction HTTP header, or URL query string for REST protocols
3661 `method-input-action` | `""` or URI SOAPAction HTTP header of service request messages
3662 `method-output-action` | `""` or URI SOAPAction HTTP header of service response messages
3663 `method-fault-action` | `""` or URI SOAPAction HTTP header of service fault messages
3664 `method-header-part` | member name of the `SOAP_ENV__Header` struct used in SOAP Header
3665 `method-input-header-part` | member name of the `SOAP_ENV__Header` struct used in SOAP Headers of requests
3666 `method-output-header-part` | member name of the `SOAP_ENV__Header` struct used in SOAP Headers of responses
3667 `method-fault` | type name of a struct or class member used in `SOAP_ENV__Details` struct
3668 `method-mime-type` | REST content type or SOAP MIME attachment content type(s)
3669 `method-input-mime-type` | REST content type or SOAP MIME attachment content type(s) of request message
3670 `method-output-mime-type` | REST content type or SOAP MIME attachment content type(s) of response message
3671 `method-style` | `document` or `rpc`
3672 `method-encoding` | `literal`, `encoded`, or a custom URI for encodingStyle of messages
3673 `method-response-encoding` | `literal`, `encoded`, or a custom URI for encodingStyle of response messages
3674 `method-protocol` | SOAP or REST, see [service directives](#directives-1)
3675 
3676 The `method-header-part` properties can be repeated for a service operation to
3677 declare multiple SOAP Header parts that the service operation requires. You
3678 can use `method-input-header-part` and `method-output-header-part` to
3679 differentiate between request and response messages.
3680 
3681 The `method-fault` property can be repeated for a service operation to declare
3682 multiple faults that the service operation may return.
3683 
3684 The `method-action` property serves two purposes:
3685 
3686 -# To set the SOAPAction header for SOAP protocols, i.e. sets the
3687  definitions/binding/operation/SOAP:operation/\@soapAction.
3688 
3689 -# To set the URL query string for endpoints with REST protocols, i.e. sets the
3690  definitions/binding/operation/HTTP:operation/\@location, which specifies
3691  a URL query string (starts with a `?`) to complete the service endpoint URL
3692  or extends the endpoint URL with a local path (starts with a `/`).
3693 
3694 Use `method-input-action` and `method-output-action` to differentiate the
3695 SOAPAction between SOAP request and response messages.
3696 
3697 You can always override the port endpoint URL and action values at runtime in
3698 the auto-generated `soap_call_prefix__func` service call (C/C++ client side)
3699 and in the auto-generated C++ proxy class service calls. A runtime NULL
3700 endpoint URL and/or action uses the defaults set by these directives.
3701 
3702 The `method-mime-type` property serves two purposes:
3703 
3704 -# To set the type of MIME/MTOM attachments used with SOAP protocols. Multiple
3705  attachment types can be declared for a SOAP service operation, i.e. adds
3706  definitions/binding/operation/input/MIME:multipartRelated/MIME:part/MIME:content/\@type
3707  for each type specified.
3708 
3709 -# To set the MIME type of a REST operation. This replaces XML declared in
3710  WSDL by definitions/binding/operation/(input|output)/MIME:mimeXml with
3711  MIME:content/\@type. Use `application/x-www-form-urlencoded` with REST POST
3712  and PUT protocols to send encoded form data automatically instead of XML.
3713  Only primitive type values can be transmitted with form data, such as
3714  numbers and strings, i.e. only types that are legal to use as
3715  [attributes members](#toxsd9-5).
3716 
3717 Use `method-input-mime-type` and `method-output-mime-type` to differentiate the
3718 attachment types between SOAP request and response messages.
3719 
3720 🔝 [Back to table of contents](#)
3721 
3722 Schema directives {#directives-3}
3723 -----------------
3724 
3725 A schema directive is of the form:
3726 
3727 ```cpp
3728 //gsoap <prefix> schema <property>: <value>
3729 ```
3730 
3731 where `<prefix>` is the XML namespace prefix of a schema. The `<property>` and
3732 `<value>` fields are one of the following:
3733 
3734 property | value
3735 --------------- | -----
3736 `namespace` | URI of the XSD targetNamespace
3737 `namespace2` | alternate URI for the XSD namespace (i.e. URI is also accepted by the XML parser)
3738 `import` | URI of imported namespace
3739 `form` | `unqualified` (default) or `qualified` local element and attribute form defaults
3740 `elementForm` | `unqualified` (default) or `qualified` local element form default
3741 `attributeForm` | `unqualified` (default) or `qualified` local attribute form default
3742 `typed` | `no` (default) or `yes` for serializers to add `xsi:type` attributes to XML
3743 
3744 To learn more about the local form defaults, see [qualified and unqualified members.](#toxsd9-6)
3745 
3746 The `typed` property is implicitly `yes` when soapcpp2 option `-t` is used.
3747 
3748 🔝 [Back to table of contents](#)
3749 
3750 Schema type directives {#directives-4}
3751 ----------------------
3752 
3753 A schema type directive is of the form:
3754 
3755 ```cpp
3756 //gsoap <prefix> schema type-<property>: <name> <value>
3757 //gsoap <prefix> schema type-<property>: <name>::<member> <value>
3758 ```
3759 
3760 where `<prefix>` is the XML namespace prefix of a schema and `<name>` is an
3761 unqualified name of a C/C++ type, and the optional `<member>` is a class/struct
3762 members or enum constant.
3763 
3764 You can describe a type:
3765 
3766 type property | value
3767 -------------------- | -----
3768 `type-documentation` | text describing the schema type
3769 `type` | same as above, shorthand form
3770 
3771 For example, you can add a description to an enumeration:
3772 
3773 ```cpp
3774 //gsoap ns schema type: Vowels The letters A, E, I, O, U, and sometimes Y
3775 //gsoap ns schema type: Vowels::Y A vowel, sometimes
3776 enum class ns__Vowels : char { A = 'A', E = 'E', I = 'I', O = 'O', U = 'U', Y = 'Y' };
3777 ```
3778 
3779 This documented enumeration maps to a simpleType restriction of `xsd:string` in
3780 the soapcpp2-generated schema:
3781 
3782 <div class="alt">
3783 ```xml
3784 <simpleType name="Vowels">
3785  <annotation>
3786  <documentation>The letters A, E, I, O, U, and sometimes Y</documentation>
3787  </annotation>
3788  <restriction base="xsd:string">
3789  <enumeration value="A"/>
3790  <enumeration value="E"/>
3791  <enumeration value="I"/>
3792  <enumeration value="O"/>
3793  <enumeration value="U"/>
3794  <enumeration value="Y">
3795  <annotation>
3796  <documentation>A vowel, sometimes</documentation>
3797  </annotation>
3798  <enumeration/>
3799  </restriction>
3800 </simpleType>
3801 ```
3802 </div>
3803 
3804 🔝 [Back to table of contents](#)
3805 
3806 Serialization rules {#rules}
3807 ===================
3808 
3809 A presentation on XML data bindings is not complete without discussing the
3810 serialization rules and options that put your data in XML on the wire or store
3811 it a file or buffer.
3812 
3813 There are several options to choose from to serialize data in XML. The choice
3814 depends on the use of the SOAP protocol or if SOAP is not required. The wsdl2h
3815 tool automates this for you by taking the WSDL transport bindings into account
3816 when generating the service functions in C and C++ that use SOAP or REST.
3817 
3818 The gSOAP tools are not limited to SOAP. The tools implement generic XML data
3819 bindings for SOAP, REST, and other uses of XML. So you can read and write XML
3820 using the serializing [operations on classes and structs](#toxsd9-13).
3821 
3822 The following sections briefly explain the serialization rules with respect to
3823 the SOAP protocol for XML Web services. A basic understanding of the SOAP
3824 protocol is useful when developing client and server applications that must
3825 interoperate with other SOAP applications.
3826 
3827 SOAP/REST Web service client and service operations are represented as
3828 functions in your gSOAP header file with the data binding interface for
3829 soapcpp2. The soapcpp2 tool will translate these function to client-side
3830 service invocation calls and server-side service operation dispatchers.
3831 
3832 A discussion of SOAP clients and servers is beyond the scope of this document.
3833 However, the SOAP options discussed here also apply to SOAP client and server
3834 development.
3835 
3836 🔝 [Back to table of contents](#)
3837 
3838 SOAP document versus rpc style {#doc-rpc}
3839 ------------------------------
3840 
3841 The `wsdl:binding/soap:binding/@style` attribute in the wsdl:binding section of
3842 a WSDL is either "document" or "rpc". The "rpc" style refers to SOAP RPC
3843 (Remote Procedure Call), which is more restrictive than the "document" style by
3844 requiring one XML element in the SOAP Body to act as the procedure name with
3845 XML subelements as its parameters.
3846 
3847 For example, the following directives in the gSOAP header file for soapcpp2
3848 declare that `DBupdate` is a SOAP RPC encoding service method:
3849 
3850 ```cpp
3851 //gsoap ns service namespace: urn:DB
3852 //gsoap ns service method-protocol: DBupdate SOAP
3853 //gsoap ns service method-style: DBupdate rpc
3854 int ns__DBupdate(...);
3855 ```
3856 
3857 The XML payload has a SOAP envelope, optional SOAP header, and a SOAP body with
3858 one element representing the operation with the parameters as subelements:
3859 
3860 <div class="alt">
3861 ```xml
3862 <SOAP-ENV:Envelope
3863  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
3864  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
3865  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3866  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
3867  xmlsn:ns="urn:DB">
3868  <SOAP-ENV:Body>
3869  <ns:DBupdate>
3870  ...
3871  </ns:DBupdate>
3872  </SOAP-ENV:Body>
3873 </SOAP-ENV:Envelope>
3874 ```
3875 </div>
3876 
3877 The "document" style puts no restrictions on the SOAP Body content. However, we
3878 recommend that the first element's tag name in the SOAP Body should be unique
3879 to each type of operation, so that the receiver can dispatch the operation
3880 based on this element's tag name. Alternatively, the HTTP URL path can be used
3881 to specify the operation, or the HTTP action header can be used to dispatch
3882 operations automatically on the server side (soapcpp2 options -a and -A).
3883 
3884 🔝 [Back to table of contents](#)
3885 
3886 SOAP literal versus encoding {#lit-enc}
3887 ----------------------------
3888 
3889 The `wsdl:operation/soap:body/@use` attribute in the wsdl:binding section of a
3890 WSDL is either "literal" or "encoded". The "encoded" use refers to the SOAP
3891 encoding rules that support id-ref multi-referenced elements to serialize
3892 data as graphs.
3893 
3894 SOAP encoding is very useful if the data internally forms a graph (including
3895 cycles) and we want the graph to be serialized in XML in a format that ensures
3896 that its structure is preserved. In that case, SOAP 1.2 encoding is the best
3897 option.
3898 
3899 SOAP encoding also adds encoding rules for [SOAP arrays](#toxsd10) to serialize
3900 multi-dimensional arrays. The use of XML attributes to exchange XML data in
3901 SOAP encoding is not permitted. The only attributes permitted are the standard
3902 XSD attributes, SOAP encoding attributes (such as for arrays), and id-ref.
3903 
3904 For example, the following directives in the gSOAP header file for soapcpp2
3905 declare that `DBupdate` is a SOAP RPC encoding service method:
3906 
3907 ```cpp
3908 //gsoap ns service namespace: urn:DB
3909 //gsoap ns service method-protocol: DBupdate SOAP
3910 //gsoap ns service method-style: DBupdate rpc
3911 //gsoap ns service method-encoding: DBupdate encoded
3912 int ns__DBupdate(...);
3913 ```
3914 
3915 The XML payload has a SOAP envelope, optional SOAP header, and a SOAP body with
3916 an encodingStyle attribute for SOAP 1.1 encoding and an element representing the
3917 operation with parameters that are SOAP 1.1 encoded:
3918 
3919 <div class="alt">
3920 ```xml
3921 <SOAP-ENV:Envelope
3922  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
3923  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
3924  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3925  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
3926  xmlsn:ns="urn:DB">
3927  <SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
3928  <ns:DBupdate>
3929  <records SOAP-ENC:arrayType="ns:record[3]">
3930  <item>
3931  <name href="#_1"/>
3932  <SSN>1234567890</SSN>
3933  </item>
3934  <item>
3935  <name>Jane</name>
3936  <SSN>1987654320</SSN>
3937  </item>
3938  <item>
3939  <name href="#_1"/>
3940  <SSN>2345678901</SSN>
3941  </item>
3942  </records>
3943  </ns:DBupdate>
3944  <id id="_1" xsi:type="xsd:string">Joe</id>
3945  </SOAP-ENV:Body>
3946 </SOAP-ENV:Envelope>
3947 ```
3948 </div>
3949 
3950 Note that the name "Joe" is shared by two records and the string is referenced
3951 by SOAP 1.1 href and id attributes.
3952 
3953 While gSOAP only introduces multi-referenced elements in the payload when they
3954 are actually multi-referenced in the data graph, other SOAP applications may
3955 render multi-referenced elements more aggressively. The example could also be
3956 rendered as:
3957 
3958 <div class="alt">
3959 ```xml
3960 <SOAP-ENV:Envelope
3961  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
3962  xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
3963  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3964  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
3965  xmlsn:ns="urn:DB">
3966  <SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
3967  <ns:DBupdate>
3968  <records SOAP-ENC:arrayType="ns:record[3]">
3969  <item href="#id1"/>
3970  <item href="#id2"/>
3971  <item href="#id3"/>
3972  </records>
3973  </ns:DBupdate>
3974  <id id="id1" xsi:type="ns:record">
3975  <name href="#id4"/>
3976  <SSN>1234567890</SSN>
3977  </id>
3978  <id id="id2" xsi:type="ns:record">
3979  <name href="#id5"/>
3980  <SSN>1987654320</SSN>
3981  </id>
3982  <id id="id3" xsi:type="ns:record">
3983  <name href="#id4"/>
3984  <SSN>2345678901</SSN>
3985  </id>
3986  <id id="id4" xsi:type="xsd:string">Joe</id>
3987  <id id="id5" xsi:type="xsd:string">Jane</id>
3988  </SOAP-ENV:Body>
3989 </SOAP-ENV:Envelope>
3990 ```
3991 </div>
3992 
3993 SOAP 1.2 encoding is cleaner and produces more accurate XML encodings of data
3994 graphs by setting the id attribute on the element that is referenced:
3995 
3996 <div class="alt">
3997 ```xml
3998 <SOAP-ENV:Envelope
3999  xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope"
4000  xmlns:SOAP-ENC="http://www.w3.org/2003/05/soap-encoding"
4001  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4002  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
4003  xmlsn:ns="urn:DB">
4004  <SOAP-ENV:Body>
4005  <ns:DBupdate SOAP-ENV:encodingStyle="http://www.w3.org/2003/05/soap-encoding">
4006  <records SOAP-ENC:itemType="ns:record" SOAP-ENC:arraySize="3">
4007  <item>
4008  <name SOAP-ENC:id="_1">Joe</name>
4009  <SSN>1234567890</SSN>
4010  </item>
4011  <item>
4012  <name>Jane</name>
4013  <SSN>1987654320</SSN>
4014  </item>
4015  <item>
4016  <name SOAP-ENC:ref="_1"/>
4017  <SSN>2345678901</SSN>
4018  </item>
4019  </records>
4020  </ns:DBupdate>
4021  </SOAP-ENV:Body>
4022 </SOAP-ENV:Envelope>
4023 ```
4024 </div>
4025 
4026 @note Some SOAP 1.2 applications consider the namespace `SOAP-ENC` of
4027 `SOAP-ENC:id` and `SOAP-ENC:ref` optional. The gSOAP SOAP 1.2 encoding
4028 serialization follows the 2007 standard, while accepting unqualified id and
4029 ref attributes.
4030 
4031 To remove all rendered id-ref multi-referenced elements in gSOAP, use the
4032 `SOAP_XML_TREE` flag to initialize the gSOAP engine context.
4033 
4034 Some XSD validation rules are turned off with SOAP encoding, because of the
4035 presence of additional attributes, such as id and ref/href, SOAP arrays with
4036 arbitrary element tags for array elements, and the occurrence of additional
4037 multi-ref elements in the SOAP 1.1 Body.
4038 
4039 The use of "literal" puts no restrictions on the XML in the SOAP Body. Full
4040 XSD validation is possible, which can be enabled with the `SOAP_XML_STRICT`
4041 flag to initialize the gSOAP engine context. However, data graphs will be
4042 serialized as trees and cycles in the data will be cut from the XML rendition.
4043 
4044 🔝 [Back to table of contents](#)
4045 
4046 SOAP 1.1 versus SOAP 1.2 {#soap}
4047 ------------------------
4048 
4049 There are two SOAP protocol versions: 1.1 and 1.2. The gSOAP tools can switch
4050 between the two versions seamlessly. You can declare the default SOAP version
4051 for a service operation as follows:
4052 
4053 ```cpp
4054 //gsoap ns service method-protocol: DBupdate SOAP1.2
4055 ```
4056 
4057 The gSOAP soapcpp2 auto-generates client and server code. At the client side,
4058 this operation sends data with SOAP 1.2 but accepts responses also in SOAP 1.1.
4059 At the server side, this operation accepts requests in SOAP 1.1 and 1.2 and
4060 will return responses in the same SOAP version.
4061 
4062 As we discussed in the previous section, the SOAP 1.2 protocol has a cleaner
4063 multi-referenced element serialization format that greatly enhances the
4064 accuracy of data graph serialization with SOAP RPC encoding and is therefore
4065 recommended.
4066 
4067 The SOAP 1.2 protocol default can also be set by importing and loading
4068 `gsoap/import/soap12.h`:
4069 
4070 ```cpp
4071 #import "soap12.h"
4072 ```
4073 
4074 🔝 [Back to table of contents](#)
4075 
4076 Non-SOAP XML serialization {#non-soap}
4077 --------------------------
4078 
4079 You can serialize data that is stored on the heap, on the stack (locals), and
4080 static data as long as the serializable (i.e. non-transient) members are
4081 properly initialized and pointers in the structures are either NULL or point to
4082 valid structures. Deserialized data is put on the heap and managed by the
4083 gSOAP engine context `struct soap`, see also [memory management](#memory).
4084 
4085 You can read and write XML directly to a file or stream with the serializing
4086 [operations on classes and structs](#toxsd9-13).
4087 
4088 To define and use XML Web service client and service operations, we can declare
4089 these operations in your gSOAP header file with the data binding interface for
4090 soapcpp2 as functions. The function are translated by soapcpp2 to client-side
4091 service invocation calls and server-side service operation dispatchers.
4092 
4093 The REST operations POST, GET, and PUT are declared with `//gsoap` directives
4094 in the gSOAP header file for soapcpp2. For example, a REST POST operation is
4095 declared as follows:
4096 
4097 ```cpp
4098 //gsoap ns service namespace: urn:DB
4099 //gsoap ns service method-protocol: DBupdate POST
4100 int ns__DBupdate(...);
4101 ```
4102 
4103 There is no SOAP Envelope and no SOAP Body in the payload for `DBupdate`. Also
4104 the XML serialization rules are identical to SOAP document/literal. The XML
4105 payload only has the operation name as an element with its parameters
4106 serialized as subelements:
4107 
4108 <div class="alt">
4109 ```xml
4110 <ns:DBupdate xmln:ns="urn:DB" ...>
4111  ...
4112 </ns:DBupdate>
4113 ```
4114 </div>
4115 
4116 To force id-ref serialization with REST similar to SOAP 1.2 multi-reference
4117 encoding, use the `SOAP_XML_GRAPH` flag to initialize the gSOAP engine context.
4118 The XML serialization includes id and ref attributes for multi-referenced
4119 elements as follows:
4120 
4121 <div class="alt">
4122 ```xml
4123 <ns:DBupdate xmln:ns="urn:DB" ...>
4124  <records>
4125  <item>
4126  <name id="_1">Joe</name>
4127  <SSN>1234567890</SSN>
4128  </item>
4129  <item>
4130  <name>Jane</name>
4131  <SSN>1987654320</SSN>
4132  </item>
4133  <item>
4134  <name ref="_1"/>
4135  <SSN>2345678901</SSN>
4136  </item>
4137  </records>
4138 </ns:DBupdate>
4139 ```
4140 </div>
4141 
4142 🔝 [Back to table of contents](#)
4143 
4144 Input and output {#io}
4145 ================
4146 
4147 Reading and writing XML from/to files, streams and string buffers is done via
4148 the managing context by setting one of the following context members that
4149 control IO sources and sinks:
4150 
4151 ```cpp
4152 soap->recvfd = fd; // an int file descriptor to read from (0 by default)
4153 soap->sendfd = fd; // an int file descriptor to write to (1 by default)
4154 soap->is = &is; // C++ only: a std::istream is object to read from
4155 soap->os = &os; // C++ only: a std::ostream os object to write to
4156 soap->is = cs; // C only: a const char* string to read from (soap->is will advance)
4157 soap->os = &cs; // C only: pointer to a const char*, will be set to point to the string output
4158 ```
4159 
4160 Normally, all of these context members are NULL, which is required to send and
4161 receive data over sockets by gSOAP clients and servers. Therefore, if you set
4162 any of these context members in a client or server application then you MUST
4163 reset them to NULL to ensure that socket communications are not blocked.
4164 
4165 Note: the use of `soap->is` and `soap->os` in C requires gSOAP 2.8.28 or later.
4166 
4167 In the following sections, we present more details on how to read and write to
4168 files and streams, and use string buffers as sources and sinks for XML data.
4169 
4170 In addition, you can set IO callback functions to handle IO at a lower level.
4171 
4172 For more details, see the [gSOAP user guide.](http://www.genivia.com/doc/soapdoc2.html)
4173 
4174 🔝 [Back to table of contents](#)
4175 
4176 Reading and writing from/to files and streams {#io1}
4177 ---------------------------------------------
4178 
4179 The default IO is standard input and output. Other sources and sinks (those
4180 listed above) will be used until you (re)set them. For example with file-based
4181 input and output:
4182 
4183 ```cpp
4184 FILE *fp = fopen("record.xml", "r");
4185 if (fp != NULL)
4186 {
4187  soap->recvfd = fileno(fp); // get file descriptor of file to read from
4188  if (soap_read_ns__record(soap, &pers1))
4189  ... // handle IO error
4190  fclose(fp);
4191  soap->recvfd = 0; // read from stdin, or -1 to block reading
4192 }
4193 
4194 FILE *fp = fopen("record.xml", "w");
4195 if (fp != NULL)
4196 {
4197  soap->sendfd = fileno(fp); // get file descriptor of file to write to
4198  if (soap_write_ns__record(soap, &pers1))
4199  ... // handle IO error
4200  fclose(fp);
4201  soap->sendfd = 1; // write to stdout, or -1 to block writing
4202 }
4203 ```
4204 
4205 Similar code with streams in C++:
4206 
4207 ```cpp
4208 #include <fstream>
4209 
4210 std::fstream fs;
4211 fs.open("record.xml", std::ios::in);
4212 if (fs)
4213 {
4214  soap->is = &fs;
4215  if (soap_read__ns__record(soap, &pers1))
4216  ... // handle IO error
4217  fs.close();
4218  soap->is = NULL;
4219 }
4220 
4221 fs.open("record.xml", std::ios::out);
4222 if (fs)
4223 {
4224  soap->os = &fs;
4225  if (soap_write__ns__record(soap, &pers1))
4226  ... // handle IO error
4227  fs.close();
4228  soap->os = NULL;
4229 }
4230 ```
4231 
4232 🔝 [Back to table of contents](#)
4233 
4234 Reading and writing from/to string buffers {#io2}
4235 ------------------------------------------
4236 
4237 For C++ we recommend to use `std::stringstream` objects from `<sstream>` as
4238 illustrated in the following example:
4239 
4240 ```cpp
4241 #include <sstream>
4242 
4243 std::stringstream ss;
4244 ss.str("..."); // XML to parse
4245 soap->is = &ss;
4246 if (soap_read__ns__record(soap, &pers1))
4247  ... // handle IO error
4248 soap->is = NULL;
4249 
4250 soap->os = &ss;
4251 if (soap_write__ns__record(soap, &pers1))
4252  ... // handle IO error
4253 soap->os = NULL;
4254 std::string s = ss.str(); // string with XML
4255 ```
4256 
4257 For C we can use `soap->is` and `soap->os` to point to strings of XML content
4258 as follows (this requires gSOAP 2.8.28 or later):
4259 
4260 ```cpp
4261 soap->is = "..."; // XML to parse
4262 if (soap_read__ns__record(soap, &pers1))
4263  ... // handle IO error
4264 soap->is = NULL;
4265 
4266 const char *cs = NULL;
4267 soap->os = &cs;
4268 if (soap_write__ns__record(soap, &pers1))
4269  ... // handle IO error
4270 soap->os = NULL;
4271 ... = cs; // string with XML (do not free(cs): managed by the context and freed with soap_end())
4272 ```
4273 
4274 Note that `soap->os` is a pointer to a `const char*` string. The pointer is
4275 set by the managing context to point to the XML data that is stored on the
4276 context-managed heap.
4277 
4278 For earlier gSOAP versions we recommend to use IO callbacks `soap->frecv` and
4279 `soap->fsend`, see the [gSOAP user guide.](http://www.genivia.com/doc/soapdoc2.html)
4280 
4281 🔝 [Back to table of contents](#)
4282 
4283 Memory management {#memory}
4284 =================
4285 
4286 Memory management with the `soap` context enables us to allocate data in
4287 context-managed heap space that can be collectively deleted. All deserialized
4288 data is placed on the context-managed heap by the gSOAP engine.
4289 
4290 🔝 [Back to table of contents](#)
4291 
4292 Memory management in C {#memory1}
4293 ----------------------
4294 
4295 When working with gSOAP in C (i.e. using wsdl2h option `-c` and soapcpp2 option
4296 `-c`), data is allocated on the managed heap with:
4297 
4298 - `void *soap_malloc(struct soap*, size_t len)`.
4299 
4300 You can also make shallow copies of data with `soap_memdup` that uses
4301 `soap_malloc` and a safe version of `memcpy` to copy a chunk of data `src` with
4302 length `len` to the context-managed heap:
4303 
4304 - `void * soap_memdup(struct soap*, const void *src, size_t len)`
4305 
4306 This function returns a pointer to the copy. This function requires gSOAP
4307 2.8.27 or later.
4308 
4309 In gSOAP 2.8.35 and later, you can use an auto-generated function to allocate
4310 and initialize data of type `T` on the managed heap:
4311 
4312 - `T * soap_new_T(struct soap*, int n)`
4313 
4314 This function returns an array of length `n` of type `T` data that is default
4315 initialized (by internally calling `soap_malloc(soap, n * sizeof(T))` and then
4316 `soap_default_T(soap, T*)` on each array value). Use `n=1` to allocate and
4317 initialize a single value.
4318 
4319 The `soap_malloc` function is a wrapper around `malloc`, but which also permits
4320 the `struct soap` context to track all heap allocations for collective deletion
4321 with `soap_end(soap)`:
4322 
4323 ```cpp
4324 #include "soapH.h"
4325 #include "ns.nsmap"
4326 ...
4327 struct soap *soap = soap_new(); // new context
4328 ...
4329 struct ns__record *record = (struct ns__record*)soap_malloc(soap, sizeof(struct ns__record));
4330 soap_default_ns__record(soap, record); // auto-generated struct initializer
4331 ...
4332 soap_destroy(soap); // only for C++, see section on C++ below
4333 soap_end(soap); // delete record and all other heap allocations
4334 soap_free(soap); // delete context
4335 ```
4336 
4337 All data on the managed heap is mass-deleted with `soap_end(soap)` which must
4338 be called before `soap_done(soap)` or `soap_free(soap)`, which end the use of
4339 the `soap` engine context and free the context, respectively. Use
4340 `soap_free(soap)` only when the context is allocated with `soap_new()`. Use
4341 `soap_done(soap)` only when the context is stack allocated (so cannot be
4342 deleted from the heap).
4343 
4344 The managed heap is checked for memory leaks when the gSOAP code is compiled
4345 with `-DDEBUG`.
4346 
4347 The soapcpp2 auto-generated deserializers in C use `soap_malloc` to allocate
4348 and populate deserialized structures, which are managed by the context for
4349 collective deletion.
4350 
4351 To make `char*` and `wchar_t*` string copies to the context-managed heap, we
4352 can use the functions:
4353 
4354 - `char *soap_strdup(struct soap*, const char *str)` and
4355 - `wchar_t *soap_wstrdup(struct soap*, const wchar_t *wstr)`.
4356 
4357 If your C compiler supports `typeof` then you can use the following macro to
4358 simplify the managed heap allocation and initialization of primitive values:
4359 
4360 ```cpp
4361 #define soap_assign(soap, lhs, rhs) (*(lhs = (typeof(lhs))soap_malloc(soap, sizeof(*lhs))) = rhs)
4362 ```
4363 
4364 Pointers to primitive values are often used for optional members. For example,
4365 assume we have the following struct:
4366 
4367 ```cpp
4368 struct ns__record
4369 {
4370  const char *name; // required name
4371  uint64_t *SSN; // optional SSN
4372  struct ns__record *spouse; // optional spouse
4373 };
4374 ```
4375 
4376 Use `soap_assign` to create a SSN value on the managed heap:
4377 
4378 ```cpp
4379 struct soap *soap = soap_new(); // new context
4380 ...
4381 struct ns__record *record = (struct ns__record*)soap_malloc(soap, sizeof(struct ns__record));
4382 soap_default_ns__record(soap, record);
4383 record->name = soap_strdup(soap, "Joe");
4384 soap_assign(soap, record->SSN, 1234567890UL);
4385 ...
4386 soap_end(soap); // delete managed soap_malloc'ed heap data
4387 soap_free(soap); // delete context
4388 ```
4389 
4390 Without the `soap_assign` macro, you will need two lines of code, one to
4391 allocate and one to assign (you should also use this if your system can run out
4392 of memory):
4393 
4394 ```cpp
4395 assert((record->SSN = (uint64_t*)soap_malloc(soap, sizeof(utint64_t))) != NULL);
4396 *record->SSN = 1234567890UL;
4397 ```
4398 
4399 The gSOAP serializer can serialize any heap, stack, or static allocated data.
4400 So we can also create a new record as follows:
4401 
4402 ```cpp
4403 struct soap *soap = soap_new(); // new context
4404 ...
4405 struct ns__record *record = (struct ns__record*)soap_malloc(soap, sizeof(struct ns__record));
4406 static uint64_t SSN = 1234567890UL;
4407 soap_default_ns__record(soap, record);
4408 record->name = "Joe";
4409 record->SSN = &SSN; // safe to use static values: the value of record->SSN is never changed by gSOAP
4410 ...
4411 soap_end(soap); // delete managed soap_malloc'ed heap data
4412 soap_free(soap); // delete context
4413 ```
4414 
4415 Use the soapcpp2 auto-generated `soap_dup_T` functions to duplicate data into
4416 another context (this requires soapcpp2 option `-Ec` to generate), here shown
4417 for C with the second argument `dst` NULL because we want to allocate a new
4418 managed structure:
4419 
4420 ```cpp
4421 struct soap *other_soap = soap_new(); // another context
4422 struct ns__record *other_record = soap_dup_ns__record(other_soap, NULL, record);
4423 ...
4424 soap_destroy(other_soap); // only for C++, see section on C++ below
4425 soap_end(other_soap); // delete other_record and all of its deep data
4426 soap_free(other_soap); // delete context
4427 ```
4428 
4429 Note that the only reason to use another context and not to use the primary
4430 context is when the primary context must be destroyed together with all of the
4431 objects it manages while some of the objects must be kept alive. If the objects
4432 that are kept alive contain deep cycles then this is the only option we have,
4433 because deep copy with a managing context detects and preserves these
4434 cycles unless the `SOAP_XML_TREE` flag is used with the context:
4435 
4436 ```cpp
4437 struct soap *other_soap = soap_new1(SOAP_XML_TREE); // another context
4438 struct ns__record *other_record = soap_dup_ns__record(other_soap, NULL, record);
4439 ```
4440 
4441 The resulting deep copy will be a full copy of the source data structure as a
4442 tree without co-referenced data (i.e. no digraph) and without cycles. Cycles
4443 are pruned and (one of the) pointers that forms a cycle is repaced by NULL.
4444 
4445 You can also deep copy into unmanaged space and use the auto-generated
4446 `soap_del_T()` function (requires soapcpp2 option `-Ed` to generate) to delete
4447 it later, but you MUST NOT do this for any data that has deep cycles in its
4448 runtime data structure:
4449 
4450 ```cpp
4451 struct ns__record *other_record = soap_dup_ns__record(NULL, NULL, record);
4452 ...
4453 soap_del_ns__record(other_record); // deep delete record data members
4454 free(other_record); // delete the record
4455 ```
4456 
4457 Cycles in the data structure will lead to non-termination when making unmanaged
4458 deep copies. Consider for example:
4459 
4460 ```cpp
4461 struct ns__record
4462 {
4463  const char *name; // required name
4464  uint64_t SSN; // required SSN
4465  struct ns__record *spouse; // optional spouse
4466 };
4467 ```
4468 
4469 The code to populate a structure with a mutual spouse relationship:
4470 
4471 ```cpp
4472 struct soap *soap = soap_new();
4473 ...
4474 struct ns__record pers1, pers2;
4475 soap_default_ns__record(soap, &pers1);
4476 soap_default_ns__record(soap, &pers2);
4477 pers1.name = "Joe"; // OK to serialize static data
4478 pers1.SSN = 1234567890;
4479 pers1.spouse = &pers2;
4480 pers2.name = soap_strdup(soap, "Jane"); // allocates and copies a string
4481 pers2.SSN = 1987654320;
4482 pers2.spouse = &pers1;
4483 ...
4484 struct ns__record *pers3 = soap_dup_ns__record(NULL, NULL, &pers1); // BAD
4485 struct ns__record *pers4 = soap_dup_ns__record(soap, NULL, &pers1); // OK
4486 soap_set_mode(soap, SOAP_XML_TREE);
4487 struct ns__record *pers5 = soap_dup_ns__record(soap, NULL, &pers1); // OK
4488 ```
4489 
4490 As we can see, the gSOAP serializer can serialize any heap, stack, or static
4491 allocated data, such as in the code above. So we can serialize the
4492 stack-allocated `pers1` record as follows:
4493 
4494 ```cpp
4495 FILE *fp = fopen("record.xml", "w");
4496 if (fp != NULL)
4497 {
4498  soap->sendfd = fileno(fp); // file descriptor to write to
4499  soap_set_mode(soap, SOAP_XML_GRAPH); // support id-ref w/o requiring SOAP
4500  soap_clr_mode(soap, SOAP_XML_TREE); // if set, clear
4501  soap_write_ns__record(soap, &pers1);
4502  fclose(fp);
4503  soap->sendfd = -1; // block further writing
4504 }
4505 ```
4506 
4507 which produces an XML document record.xml that is similar to:
4508 
4509 <div class="alt">
4510 ```xml
4511 <ns:record xmlns:ns="urn:types" id="Joe">
4512  <name>Joe</name>
4513  <SSN>1234567890</SSN>
4514  <spouse id="Jane">
4515  <name>Jane</name>
4516  <SSN>1987654320</SSN>
4517  <spouse ref="#Joe"/>
4518  </spouse>
4519 </ns:record>
4520 ```
4521 </div>
4522 
4523 Deserialization of an XML document with a SOAP 1.1/1.2 encoded id-ref graph
4524 leads to the same non-termination problem when we later try to copy the data
4525 into unmanaged memory heap space:
4526 
4527 ```cpp
4528 struct soap *soap = soap_new1(SOAP_XML_GRAPH); // support id-ref w/o SOAP
4529 ...
4530 struct ns__record pers1;
4531 FILE *fp = fopen("record.xml", "r");
4532 if (fp != NULL)
4533 {
4534  soap->recvfd = fileno(fp);
4535  if (soap_read_ns__record(soap, &pers1))
4536  ... // handle IO error
4537  fclose(fp);
4538  soap->recvfd = -1; // blocks further reading
4539 }
4540 ...
4541 struct ns__record *pers3 = soap_dup_ns__record(NULL, NULL, &pers1); // BAD
4542 struct ns__record *pers4 = soap_dup_ns__record(soap, NULL, &pers1); // OK
4543 soap_set_mode(soap, SOAP_XML_TREE);
4544 struct ns__record *pers5 = soap_dup_ns__record(soap, NULL, &pers1); // OK
4545 ```
4546 
4547 Copying data with `soap_dup_T(soap)` into managed heap memory space is always
4548 safe. Copying into unmanaged heap memory space requires diligence. But
4549 deleting unmanaged data is easy with `soap_del_T()`.
4550 
4551 You can also use `soap_del_T()` to delete structures that you created in C, but
4552 only if these structures are created with `malloc` and do NOT contain pointers
4553 to stack and static data.
4554 
4555 You can unlink one or more allocated objects from the managed heap to allow the
4556 object to live after `soap_end(soap)` by using:
4557 
4558 - `void soap_unlink(struct soap *soap, void *ptr)`
4559 
4560 The unlinked heap-allocated data pointed to by `ptr` can be accessed after
4561 `soap_end(soap)`. Do not forget to free the data with `free(ptr)`. Be aware
4562 that `soap_unlink(soap, ptr)` does not perform a deep unlinkage. If `ptr` is a
4563 struct, pointer members will become invalid when pointing to objects on the
4564 managed heap. Use `soap_unlink(soap, ptr->member)` to unlink `member` as well.
4565 
4566 Finally, when data is allocated in managed memory heap space, either explicitly
4567 with the allocation functions shown above or by the gSOAP deserializers, you
4568 can delegate the management and deletion of this data to another `struct soap`
4569 context. That context will be responsible to delete the data with
4570 `soap_end(soap)` later:
4571 
4572 - `void delegate_deletion(struct soap *soap_from, struct soap *soap_to)`
4573 
4574 This allows the `soap_from` context to be deleted with `soap_free(soap_from)`
4575 (assuming it is allocated with `soap_new()`, use `soap_done(soap_from)` when
4576 `soap_from` is stack-allocated) while the managed data remains intact. You
4577 can use this function any time, to delegate management and deletion to another
4578 context `soap_to` and then continue with the current context. You can also use
4579 different source `soap_from` contexts to delegate management and deletion to
4580 the other `soap_to` context. To mass delete all managed data, use
4581 `soap_end(soap_to)`.
4582 
4583 🔝 [Back to table of contents](#)
4584 
4585 Memory management in C++ {#memory2}
4586 ------------------------
4587 
4588 When working with gSOAP in C++, the gSOAP engine allocates data on a managed
4589 heap using `soap_new_T(soap)` to allocate a type with type name `T`. Managed
4590 heap allocation is tracked by the `struct soap` context for collective deletion
4591 with `soap_destroy(soap)` for structs, classes, and templates and with
4592 `soap_end(soap)` for everything else.
4593 
4594 You should only use `soap_malloc(struct soap*, size_t len)` to allocate
4595 primitive types, but `soap_new_T()` is preferred. The auto-generated `T *
4596 soap_new_T(struct soap*)` returns data allocated on the managed heap for type
4597 `T`. The data is mass-deleted with `soap_destroy(soap)` followed by
4598 `soap_end(soap)`.
4599 
4600 The `soap_new_T` functions return NULL when allocation fails. C++ exceptions
4601 are never raised by gSOAP code when data is allocated, unless `SOAP_NOTHROW`
4602 (set to `(std::nothrow)`) is redefined to permit `new` to throw exceptions.
4603 
4604 There are four variations of `soap_new_T()` to allocate data of type `T` that
4605 soapcpp2 auto-generates:
4606 
4607 - `T * soap_new_T(struct soap*)` returns a new instance of `T` that is default
4608  initialized. For classes, initialization is internally performed using the
4609  soapcpp2 auto-generated `void T::soap_default(struct soap*)` method of the
4610  class, but ONLY IF the soapcpp2 auto-generated default constructor is used
4611  that invokes `soap_default()` and was not replaced by a user-defined default
4612  constructor.
4613 
4614 - `T * soap_new_T(struct soap*, int n)` returns an array of `n` new instances of
4615  `T`. The instances in the array are default initialized as described above.
4616 
4617 - `T * soap_new_req_T(struct soap*, ...)` (structs and classes only) returns a
4618  new instance of `T` and sets the required data members to the values
4619  specified in `...`. The required data members are those with nonzero
4620  minOccurs, see the subsections on
4621  [(smart) pointer members and their occurrence constraints](#toxsd9-8) and
4622  [container and array members and their occurrence constraints](#toxsd9-9).
4623 
4624 - `T * soap_new_set_T(struct soap*, ...)` (structs and classes only) returns a
4625  new instance of `T` and sets the public/serializable data members to the values
4626  specified in `...`.
4627 
4628 The above functions can be invoked with a NULL `soap` context, but you are then
4629 responsible to use `delete T` to remove this instance from the unmanaged heap.
4630 
4631 For example, to allocate a managed `std::string` you can use:
4632 
4633 ```cpp
4634 std::string *s = soap_new_std__string(soap);
4635 ```
4636 
4637 Primitive types and arrays of these are allocated with `soap_malloc`
4638 (`soap_new_T` calls `soap_malloc` for primitive type `T`). All primitive types
4639 (i.e. no classes, structs, class templates, containers, and smart pointers) are
4640 allocated with `soap_malloc` for reasons of efficiency.
4641 
4642 You can use a C++ template to simplify the managed allocation and initialization
4643 of primitive values as follows (this is for primitive types only):
4644 
4645 ```cpp
4646 template<class T>
4647 T * soap_make(struct soap *soap, T val) throw (std::bad_alloc)
4648 {
4649  T *p = (T*)soap_malloc(soap, sizeof(T));
4650  if (p == NULL)
4651  throw std::bad_alloc;
4652  *p = val;
4653  return p;
4654 }
4655 ```
4656 
4657 For example, assuming we have the following class:
4658 
4659 ```cpp
4660 class ns__record
4661 {
4662  public:
4663  std::string name; // required name
4664  uint64_t *SSN; // optional SSN
4665  ns__record *spouse; // optional spouse
4666 };
4667 ```
4668 
4669 You can instantiate a record by using the auto-generated
4670 `soap_new_set_ns__record` and use `soap_make` to create a SSN value on the
4671 managed heap as follows:
4672 
4673 ```cpp
4674 soap *soap = soap_new(); // new context
4675 ...
4676 ns__record *record = soap_new_set_ns__record(
4677  soap,
4678  "Joe",
4679  soap_make<uint64_t>(soap, 1234567890UL),
4680  NULL);
4681 ...
4682 soap_destroy(soap); // delete record and all other managed instances
4683 soap_end(soap); // delete managed soap_malloc'ed heap data
4684 soap_free(soap); // delete context
4685 ```
4686 
4687 All data on the managed heap is mass-deleted with `soap_end(soap)` which must
4688 be called before `soap_done(soap)` or `soap_free(soap)`, which end the use of
4689 the `soap` engine context and free the context, respectively. Use
4690 `soap_free(soap)` only when the context is allocated with `soap_new()`. Use
4691 `soap_done(soap)` only when the context is stack allocated (so cannot be
4692 deleted from the heap).
4693 
4694 The managed heap is checked for memory leaks when the gSOAP code is compiled
4695 with `-DDEBUG`.
4696 
4697 Note however that the gSOAP serializer can serialize any heap, stack, or static
4698 allocated data. So we can also create a new record as follows:
4699 
4700 ```cpp
4701 uint64_t SSN = 1234567890UL;
4702 ns__record *record = soap_new_set_ns__record(soap, "Joe", &SSN, NULL);
4703 ```
4704 
4705 which will be fine to serialize this record as long as the local `SSN`
4706 stack-allocated value remains in scope when invoking the serializer and/or
4707 using `record`. It does not matter if `soap_destroy` and `soap_end` are called
4708 beyond the scope of `SSN`.
4709 
4710 To facilitate class methods to access the managing context, we can add a soap
4711 context pointer to a class/struct:
4712 
4713 ```cpp
4714 class ns__record
4715 {
4716  ...
4717  void create_more(); // needs a context to create more internal data
4718  protected:
4719  struct soap *soap; // the context that manages this instance, or NULL
4720 };
4721 ```
4722 
4723 The context is set when invoking `soap_new_T` (and similar) with a non-NULL
4724 context argument.
4725 
4726 You can also use a template when an array of pointers to values is required.
4727 To create an array of pointers to values, define the following template:
4728 
4729 ```cpp
4730 template<class T>
4731 T **soap_make_array(struct soap *soap, T* array, int n) throw (std::bad_alloc)
4732 {
4733  T **p = (T**)soap_malloc(soap, n * sizeof(T*));
4734  if (p == NULL)
4735  throw std::bad_alloc;
4736  for (int i = 0; i < n; ++i)
4737  p[i] = &array[i];
4738  return p;
4739 }
4740 ```
4741 
4742 The `array` parameter is a pointer to an array of `n` values. The template
4743 returns an array of `n` pointers that point to the values in that array:
4744 
4745 ```cpp
4746 // create an array of 100 pointers to 100 records
4747 int n = 100;
4748 ns__record **precords = soap_make_array(soap, soap_new_ns__record(soap, n), n);
4749 for (int i = 0; i < n; ++i)
4750 {
4751  precords[i]->name = "...";
4752  precords[i]->SSN = soap_make<uint64_t>(1234567890UL + i);
4753 }
4754 ```
4755 
4756 Note that `soap_new_ns__record(soap, n)` returns a pointer to an array of `n`
4757 records, which is then used to create an array of `n` pointers to these records.
4758 
4759 Use the soapcpp2 auto-generated `soap_dup_T` functions to duplicate data into
4760 another context (this requires soapcpp2 option `-Ec` to generate), here shown
4761 for C++ with the second argument `dst` NULL to allocate a new managed object:
4762 
4763 ```cpp
4764 soap *other_soap = soap_new(); // another context
4765 ns__record *other_record = soap_dup_ns__record(other_soap, NULL, record);
4766 ...
4767 soap_destroy(other_soap); // delete record and other managed instances
4768 soap_end(other_soap); // delete other data (the SSNs on the heap)
4769 soap_free(other_soap); // delete context
4770 ```
4771 
4772 To duplicate base and derived instances when a base class pointer or reference
4773 is provided, use the auto-generated method `T * T::soap_dup(struct soap*)`:
4774 
4775 ```cpp
4776 soap *other_soap = soap_new(); // another context
4777 ns__record *other_record = record->soap_dup(other_soap);
4778 ...
4779 soap_destroy(other_soap); // delete record and other managed instances
4780 soap_end(other_soap); // delete other data (the SSNs on the heap)
4781 soap_free(other_soap); // delete context
4782 ```
4783 
4784 Note that the only reason to use another context and not to use the primary
4785 context is when the primary context must be destroyed together with all of the
4786 objects it manages while some of the objects must be kept alive. If the objects
4787 that are kept alive contain deep cycles then this is the only option we have,
4788 because deep copy with a managing context detects and preserves these
4789 cycles unless the `SOAP_XML_TREE` flag is used with the context:
4790 
4791 ```cpp
4792 soap *other_soap = soap_new1(SOAP_XML_TREE); // another context
4793 ns__record *other_record = record->soap_dup(other_soap); // deep tree copy
4794 ```
4795 
4796 The resulting deep copy will be a full copy of the source data structure as a
4797 tree without co-referenced data (i.e. no digraph) and without cycles. Cycles
4798 are pruned and (one of the) pointers that forms a cycle is repaced by NULL.
4799 
4800 You can also deep copy into unmanaged space and use the auto-generated
4801 `soap_del_T()` function or the `T::soap_del()` method (requires soapcpp2 option
4802 `-Ed` to generate) to delete it later, but we MUST NOT do this for any data
4803 that has deep cycles in its runtime data structure graph:
4804 
4805 ```cpp
4806 ns__record *other_record = record->soap_dup(NULL);
4807 ...
4808 other_record->soap_del(); // deep delete record data members
4809 delete other_record; // delete the record
4810 ```
4811 
4812 Cycles in the data structure will lead to non-termination when making unmanaged
4813 deep copies. Consider for example:
4814 
4815 ```cpp
4816 class ns__record
4817 {
4818  const char *name; // required name
4819  uint64_t SSN; // required SSN
4820  ns__record *spouse; // optional spouse
4821 };
4822 ```
4823 
4824 The code to populate a structure with a mutual spouse relationship:
4825 
4826 ```cpp
4827 soap *soap = soap_new();
4828 ...
4829 ns__record pers1, pers2;
4830 pers1.name = "Joe";
4831 pers1.SSN = 1234567890;
4832 pers1.spouse = &pers2;
4833 pers2.name = "Jane";
4834 pers2.SSN = 1987654320;
4835 pers2.spouse = &pers1;
4836 ...
4837 ns__record *pers3 = soap_dup_ns__record(NULL, NULL, &pers1); // BAD
4838 ns__record *pers4 = soap_dup_ns__record(soap, NULL, &pers1); // OK
4839 soap_set_mode(soap, SOAP_XML_TREE);
4840 ns__record *pers5 = soap_dup_ns__record(soap, NULL, &pers1); // OK
4841 ```
4842 
4843 Note that the gSOAP serializer can serialize any heap, stack, or static
4844 allocated data, such as in the code above. So we can serialize the
4845 stack-allocated `pers1` record as follows:
4846 
4847 ```cpp
4848 FILE *fp = fopen("record.xml", "w");
4849 if (fp != NULL)
4850 {
4851  soap->sendfd = fileno(fp); // file descriptor to write to
4852  soap_set_mode(soap, SOAP_XML_GRAPH); // support id-ref w/o requiring SOAP
4853  soap_clr_mode(soap, SOAP_XML_TREE); // if set, clear
4854  if (soap_write_ns__record(soap, &pers1))
4855  ... // handle IO error
4856  fclose(fp);
4857  soap->sendfd = -1; // block further writing
4858 }
4859 ```
4860 
4861 which produces an XML document record.xml that is similar to:
4862 
4863 <div class="alt">
4864 ```xml
4865 <ns:record xmlns:ns="urn:types" id="Joe">
4866  <name>Joe</name>
4867  <SSN>1234567890</SSN>
4868  <spouse id="Jane">
4869  <name>Jane</name>
4870  <SSN>1987654320</SSN>
4871  <spouse ref="#Joe"/>
4872  </spouse>
4873 </ns:record>
4874 ```
4875 </div>
4876 
4877 Deserialization of an XML document with a SOAP 1.1/1.2 encoded id-ref graph
4878 leads to the same non-termination problem when we later try to copy the data
4879 into unmanaged space:
4880 
4881 ```cpp
4882 soap *soap = soap_new1(SOAP_XML_GRAPH); // support id-ref w/o SOAP
4883 ...
4884 ns__record pers1;
4885 FILE *fp = fopen("record.xml", "r");
4886 if (fp != NULL)
4887 {
4888  soap->recvfd = fileno(fp); // file descriptor to read from
4889  if (soap_read_ns__record(soap, &pers1))
4890  ... // handle IO error
4891  fclose(fp);
4892  soap->recvfd = -1; // block further reading
4893 }
4894 ...
4895 ns__record *pers3 = soap_dup_ns__record(NULL, NULL, &pers1); // BAD
4896 ns__record *pers4 = soap_dup_ns__record(soap, NULL, &pers1); // OK
4897 soap_set_mode(soap, SOAP_XML_TREE);
4898 ns__record *pers5 = soap_dup_ns__record(soap, NULL, &pers1); // OK
4899 ```
4900 
4901 Copying data with `soap_dup_T(soap)` into managed space is always safe. Copying
4902 into unmanaged space requires diligence. But deleting unmanaged data is easy
4903 with `soap_del_T()`.
4904 
4905 You can also use `soap_del_T()` to delete structures in C++, but only if these
4906 structures are created with `new` (and `new []` for arrays when applicable) for
4907 classes, structs, and class templates and with `malloc` for anything else, and
4908 the structures do NOT contain pointers to stack and static data.
4909 
4910 You can unlink one or more allocated objects from the managed heap to allow the
4911 object to live after `soap_destroy(soap)` and `soap_end(soap)` by using:
4912 
4913 - `void soap_unlink(struct soap *soap, void *ptr)`
4914 
4915 The unlinked heap-allocated data pointed to by `ptr` can be accessed after
4916 `soap_destroy(soap)` and `soap_end(soap)`. Do not forget to free the data with
4917 `delete ptr` (C++ class instance only) or with `free(ptr)` (non-class data).
4918 Be aware that `soap_unlink(soap, ptr)` does not perform a deep unlinkage. If
4919 `ptr` is a struct or class, pointer members will become invalid when pointing
4920 to objects on the managed heap. Use `soap_unlink(soap, ptr->member)` to unlink
4921 `member` as well.
4922 
4923 Finally, when data is allocated in managed memory heap space, either explicitly
4924 with the allocation functions shown above or by the gSOAP deserializers, you
4925 can delegate the management and deletion of this data to another `struct soap`
4926 context. That context will be responsible to delete the data with
4927 `soap_destroy(soap)` and `soap_end(soap)` later:
4928 
4929 - `void delegate_deletion(struct soap *soap_from, struct soap *soap_to)`
4930 
4931 This allows the `soap_from` context to be deleted with `soap_free(soap_from)`
4932 (assuming it is allocated with `soap_new()`, use `soap_done(soap_from)` when
4933 `soap_from` is stack-allocated) while the managed data remains intact. You
4934 can use this function any time, to delegate management and deletion to another
4935 context `soap_to` and then continue with the current context. You can also use
4936 different source `soap_from` contexts to delegate management and deletion to
4937 the other `soap_to` context. To mass delete all managed data, use
4938 `soap_destroy(soap_to)` followed by `soap_end(soap_to)`.
4939 
4940 🔝 [Back to table of contents](#)
4941 
4942 Context flags to initialize the soap struct {#flags}
4943 ===========================================
4944 
4945 There are several context initialization flags and context mode flags to
4946 control XML serialization at runtime. The flags are set with `soap_new1()` to
4947 allocate and initialize a new context:
4948 
4949 ```cpp
4950 struct soap *soap = soap_new1(<flag> | <flag> ... | <flag>);
4951 ...
4952 soap_destroy(soap); // delete objects
4953 soap_end(soap); // delete other data and temp data
4954 soap_free(soap); // free context
4955 ```
4956 
4957 and with `soap_init1()` for stack-allocated contexts:
4958 
4959 ```cpp
4960 struct soap soap;
4961 soap_init1(&soap, <flag> | <flag> ... | <flag>);
4962 ...
4963 soap_destroy(&soap); // delete objects
4964 soap_end(&soap); // delete other data and temp data
4965 soap_done(&soap); // clear context
4966 ```
4967 
4968 where `<flag>` is one of:
4969 
4970 - `SOAP_C_UTFSTRING`: enables all `std::string` and `char*` strings to
4971  contain UTF-8 content. This option is recommended.
4972 
4973 - `SOAP_C_NILSTRING`: treat empty strings as if they were NULL pointers, i.e.
4974  omits elements and attributes when empty.
4975 
4976 - `SOAP_XML_STRICT`: strictly validates XML while deserializing. Should not be
4977  used together with SOAP 1.1/1.2 encoding style of messaging. Use soapcpp2
4978  option `-s` to hard code `SOAP_XML_STRICT` in the generated serializers. Not
4979  recommended with SOAP 1.1/1.2 encoding style messaging.
4980 
4981 - `SOAP_XML_INDENT`: produces indented XML.
4982 
4983 - `SOAP_XML_CANONICAL`: c14n canonocalization, removes unused `xmlns` bindings
4984  and adds them to appropriate places by applying c14n normalization rules.
4985  Should not be used together with SOAP 1.1/1.2 encoding style messaging.
4986 
4987 - `SOAP_XML_TREE`: write tree XML without id-ref, while pruning data structure
4988  cycles to prevent nontermination of the serializer for cyclic structures.
4989 
4990 - `SOAP_XML_GRAPH`: write graph (digraph and cyclic graphs with shared pointers
4991  to objects) using id-ref attributes. That is, XML with SOAP multi-ref
4992  encoded id-ref elements. This is a structure-preserving serialization format,
4993  because co-referenced data and also cyclic relations are accurately represented.
4994 
4995 - `SOAP_XML_DEFAULTNS`: uses xmlns default namespace declarations, assuming
4996  that the schema attribute form is "qualified" by default (be warned if it is
4997  not, since attributes in the null namespace will get bound to namespaces!).
4998 
4999 - `SOAP_XML_NIL`: emit empty element with `xsi:nil` for all NULL pointers
5000  serialized.
5001 
5002 - `SOAP_XML_IGNORENS`: the XML parser ignores XML namespaces, i.e. element and
5003  attribute tag names match independent of their namespace.
5004 
5005 - `SOAP_XML_NOTYPE`: removes all `xsi:type` attribuation. This option is usually
5006  not needed unless the receiver rejects all `xsi:type` attributes. This option
5007  may affect the quality of the deserializer, which relies on `xsi:type`
5008  attributes to distinguish base class instances from derived class instances
5009  transported in the XML payloads.
5010 
5011 - `SOAP_IO_CHUNK`: to enable HTTP chunked transfers.
5012 
5013 - `SOAP_IO_STORE`: full buffering of outbound messages.
5014 
5015 - `SOAP_ENC_ZLIB`: compress messages, requires compiling with `-DWITH_GZIP` and
5016  linking with zlib (`-lz`).
5017 
5018 - `SOAP_ENC_MIME`: enable MIME attachments, see
5019  [MIME/MTOM attachment binary types](#toxsd10-3).
5020 
5021 - `SOAP_ENC_MTOM`: enable MTOM attachments, see
5022  [MIME/MTOM attachment binary types](#toxsd10-3).
5023 
5024 @note C++ Web service proxy and service classes have their own context, either
5025 as a base class (soapcpp2 option -i) or as a data member `soap` that points to
5026 a context (soapcpp2 option -j). These contexts are allocated when the proxy or
5027 service is instantiated with context flags that are passed to the constructor.
5028 
5029 🔝 [Back to table of contents](#)
5030 
5031 Context parameter settings {#params}
5032 ==========================
5033 
5034 After allocation and initializtion of a `struct soap` context, several context
5035 parameters can be set (some parameters may require 2.8.31 and later versions):
5036 
5037 - `unsigned int soap::maxlevel` is the maximum XML nesting depth levels that
5038  the parser permits. Default initialized to `SOAP_MAXLEVEL` (10000), which is
5039  a redefinable macro in stdsoap2.h. Set `soap::maxlevel` to a lower value to
5040  restrict XML parsing nesting depth.
5041 
5042 - `long soap::maxlength` is the maximum string content length if not already
5043  constrained by an XML schema validation `maxLength` constraint. Zero means
5044  unlimited string lengths are permitted (unless restricted by XML schema
5045  `maxLength`). Default initialized to `SOAP_MAXLENGTH` (0), which is a
5046  redefinable macro in stdsoap2.h. Set `soap::maxlength` to a positive value
5047  to restrict the number of (wide) characters in strings parsed, restrict
5048  hexBinary byte length, and restrict base64Binary byte length.
5049 
5050 - `size_t soap::maxoccurs` is the maximum number of array or container elements
5051  permitted by the parser. Must be greater than zero (0). Default initialized
5052  to `SOAP_MAXOCCURS` (100000), which is a redefinable macro in stdsoap2.h.
5053  Set `soap::maxoccurs` to a positive value to restrict the number of array and
5054  container elements that can be parsed.
5055 
5056 - `soap::version` is the SOAP version used, with 0 for non-SOAP, 1 for SOAP1.1,
5057  and 2 for SOAP1.2. This value is normally set by web service operations, and
5058  is otherwise 0 (non-SOAP). Use `soap_set_version(struct soap*, short)` to
5059  set the value. This controls XML namespaces and SOAP id-ref serialization
5060  when applicable with an encodingStyle (see below).
5061 
5062 - `const char *soap::encodingStyle` is a string that is used with SOAP
5063  encoding, normally NULL for non-SOAP XML. Set this string to "" (empty
5064  string) to enable SOAP encoding style, which supports id-ref graph
5065  serialization (see also the `SOAP_XML_GRAPH` [context flag](#flags)).
5066 
5067 - `int soap::recvfd` is the file descriptor to read and parse source data from.
5068  Default initialized to 0 (stdin). See also [input and output](#io).
5069 
5070 - `int soap::sendfd` is the file descriptor to write data to. Default
5071  initialized to 1 (stdout). See also [input and output](#io).
5072 
5073 - `const char *is` for C: string to read and parse source data from, overriding
5074  the `recvfd` source. Normally NULL. This value must be reset to NULL or
5075  the parser will continue to read from this string content until the NUL
5076  character. See also [input and output](#io).
5077 
5078 - `std::istream *is` for C++: an input stream to read and parse source data
5079  from, overriding the `recvfd` source. Normally NULL. This value must be
5080  reset to NULL or the parser will continue to read from this stream until EOF.
5081  See also [input and output](#io).
5082 
5083 - `const char **os` for C: points to a string (a `const char *`) that will be
5084  set to point to the string output. Normally NULL. This value must be reset
5085  to NULL or the next output will result in reassigning the pointer to point to
5086  the next string that is output. The strings are automatically deallocated by
5087  `soap_end(soap)`. See also [input and output](#io).
5088 
5089 - `std::ostream *os` for C++: an output stream to write output to. Normally
5090  NULL. This value must be reste to NULL or the next output will be send to
5091  this stream. See also [input and output](#io).
5092 
5093 🔝 [Back to table of contents](#)
5094 
5095 Error handling and reporting {#errors}
5096 ============================
5097 
5098 The gSOAP API functions return `SOAP_OK` (zero) or a non-zero error code. The
5099 error code is stored in `int soap::error` of the current `struct soap` context.
5100 Error messages can be displayed with:
5101 
5102 - `void soap_stream_fault(struct soap*, std::ostream &os)` for C++ only, prints
5103  the error message to an output stream.
5104 
5105 - `void soap_print_fault(struct soap*, FILE *fd)` prints the error message to a
5106  FILE descriptor.
5107 
5108 - `void soap_sprint_fault(struct soap*, char *buf, size_t len)` saves the error
5109  message to a fixed-size buffer allocated with a maximum length.
5110 
5111 - `void soap_print_fault_location(struct soap*, FILE *fd)` prints the location
5112  and part of the XML where the parser encountered an error.
5113 
5114 C++ exceptions are never raised by gSOAP code, even when data is allocated.
5115 (That is unless the `SOAP_NOTHROW` macro (set to `(std::nothrow)` by default)
5116 is redefined to permit `new` to throw exceptions.)
5117 
5118 A `SOAP_EOM` error code is returned when memory was exhausted during
5119 processing of input and/or output of data.
5120 
5121 An EOF (`SOAP_EOF` or -1) error code is returned when the parser has hit EOF
5122 but expected more input, or when socket communications timed out. In addition
5123 to the `SOAP_EOF` error, the `int soap::errnum` of the `struct soap` context is
5124 set to the `errno` value of the operation that failed. For timeouts, the
5125 `soap::ernum` value is always 0 instead of an `errno` error code.
5126 
5127 Use `soap_xml_error_check(soap->error)` to check for XML errors. This returns
5128 true (non-zero) when a parsing and validation error has occurred.
5129 
5130 For example:
5131 
5132 ```cpp
5133 #include <sstream>
5134 
5135 struct soap *soap = soap_new1(SOAP_XML_INDENT | SOAP_XML_STRICT | SOAP_XML_TREE);
5136 struct ns__record person;
5137 std::stringstream ss;
5138 ss.str("..."); // XML to parse
5139 soap->is = &ss;
5140 if (soap_read__ns__record(soap, &person))
5141 {
5142  if (soap_xml_error_check(soap->error))
5143  std::cerr << "XML parsing error!" << std::endl;
5144  else
5145  soap_stream_fault(soap, std::cerr);
5146 }
5147 else
5148 {
5149  ... // all OK, use person record
5150 }
5151 soap_destroy(soap); // delete objects
5152 soap_end(soap); // delete other data and temp data
5153 soap_free(soap); // free context
5154 ```
5155 
5156 When deploying your application on UNIX and Linux systems, UNIX signal handlers
5157 should be added to your code handle signals, in particular `SIGPIPE`:
5158 
5159 ```cpp
5160 signal(SIGPIPE, sigpipe_handler);
5161 ```
5162 
5163 where the `sigpipe_handler` is a function:
5164 
5165 ```cpp
5166 void sigpipe_handler(int x) { }
5167 ```
5168 
5169 Other UNIX signals may have to be handled as well.
5170 
5171 The gSOAP engine is designed for easy memory cleanup after being interrupted.
5172 Use `soap_destroy(soap)` and `soap_end(soap)`, after which the `soap` context
5173 can be reused.
5174 
5175 🔝 [Back to table of contents](#)
5176 
5177 Features and limitations {#features}
5178 ========================
5179 
5180 In general, to use the generated code:
5181 
5182 - Make sure to `#include "soapH.h"` in your code and also define a namespace
5183  table or `#include "ns.nsmap"` with the generated table, where `ns` is the
5184  namespace prefix for services.
5185 
5186 - Use soapcpp2 option -j (C++ only) to generate C++ proxy and service objects.
5187  The auto-generated files include documented inferfaces. Compile with
5188  soapC.cpp and link with -lgsoap++, or alternatively compile stdsoap2.cpp.
5189 
5190 - Without soapcpp2 option -j: client-side uses the auto-generated
5191  soapClient.cpp and soapC.cpp (or C versions of those). Compile and link with
5192  -lgsoap++ (-lgsoap for C), or alternatively compile stdsoap2.cpp
5193  (stdsoap2.c for C).
5194 
5195 - Without soapcpp2 option -j: server-side uses the auto-generated
5196  soapServer.cpp and soapC.cpp (or C versions of those). Compile and link with
5197  -lgsoap++ (-lgsoap for C), or alternatively compile stdsoap2.cpp (stdsoap2.c
5198  for C).
5199 
5200 - Use `soap_new()` or `soap_new1(int flags)` to allocate and initialize a
5201  heap-allocated context with or without flags. Delete this context with
5202  `soap_free(struct soap*)`, but only after `soap_destroy(struct soap*)` and
5203  `soap_end(struct soap*)`.
5204 
5205 - Use `soap_init(struct *soap)` or `soap_init1(struct soap*, int flags)` to
5206  initialize a stack-allocated context with or without flags. End the use of
5207  this context with `soap_done(struct soap*)`, but only after
5208  `soap_destroy(struct soap*)` and `soap_end(struct soap*)`.
5209 
5210 Additional notes with respect to the wsdl2h and soapcpp2 tools:
5211 
5212 - Nested classes, structs, and unions in a gSOAP header file are unnested by
5213  soapcpp2.
5214 
5215 - Use `#import "file.h"` instead of `#include` to import other header files in
5216  a gSOAP header file for soapcpp2. The `#include`, `#define`, and `#pragma`
5217  are accepted by soapcpp2, but are moved to the very start of the generated
5218  code for the C/C++ compiler to include before all generated definitions.
5219  Often it is useful to add an `#include` with a [volatile type](#toxsd9-2)
5220  that includes the actual type declaration, and to ensure transient types are
5221  declared when these are used in a data binding interface declared in a gSOAP
5222  header file for soapcpp2.
5223 
5224 - To remove any SOAP-specific bindings, use soapcpp2 option `-0`.
5225 
5226 - A gSOAP header file for soapcpp2 should not include any code statements, only
5227  data type declarations. This includes constructor initialization lists that are
5228  not permitted. Use member initializations instead.
5229 
5230 - C++ namespaces are supported. Use wsdl2h option `-qname`. Or add a `namespace
5231  name { ... }` to the header file, but the `{ ... }` MUST cover the entire
5232  header file content from begin to end.
5233 
5234 - Optional XML DOM support can be used to store mixed content or literal XML
5235  content. Otherwise, mixed content may be lost. Use wsdl2h option `-d` for
5236  XML DOM support and compile and link with `dom.c` or `dom.cpp`. For details,
5237  see [XML DOM and XPath](http://www.genivia.com/doc/dom/html).
5238 
5239 🔝 [Back to table of contents](#)
5240 
5241 Removing SOAP namespaces from XML payloads {#nsmap}
5242 ==========================================
5243 
5244 The soapcpp2 tool generates a `.nsmap` file that includes two bindings for SOAP
5245 namespaces. We can remove all SOAP namespaces (and SOAP processing logic) with
5246 soapcpp2 option `-0` or by simply setting the two entries to NULL:
5247 
5248 ```cpp
5249 struct Namespace namespaces[] =
5250 {
5251  {"SOAP-ENV", NULL, NULL, NULL},
5252  {"SOAP-ENC", NULL, NULL, NULL},
5253  ...
5254 };
5255 ```
5256 
5257 Note that once the `.nsmap` is generated, you can copy-paste the content into
5258 your project code. However, if we rerun wsdl2h on updated WSDL/XSD files or
5259 `typemap.dat` declarations then we need to use the updated table.
5260 
5261 In cases that no XML namespaces are used at all, for example with
5262 [XML-RPC](http://www.genivia.com/doc/xml-rpc-json/html), you may use an empty
5263 namespace table:
5264 
5265 ```cpp
5266 struct Namespace namespaces[] = {{NULL,NULL,NULL,NULL}};
5267 ```
5268 
5269 However, beware that any built-in xsi attributes that are rendered will lack
5270 the proper namespace binding. At least we suggest to use `SOAP_XML_NOTYPE` for
5271 this reason.
5272 
5273 🔝 [Back to table of contents](#)
5274 
5275 Examples {#examples}
5276 ========
5277 
5278 Select the project files below to peruse the source code examples.
5279 
5280 🔝 [Back to table of contents](#)
5281 
5282 Source files
5283 ------------
5284 
5285 - `address.xsd` Address book schema
5286 - `address.cpp` Address book app (reads/writes address.xml file)
5287 - `addresstypemap.dat` Schema namespace prefix name preference for wsdl2h
5288 - `graph.h` Graph data binding (tree, digraph, cyclic graph)
5289 - `graph.cpp` Test graph serialization as tree, digraph, and cyclic
5290 
5291 🔝 [Back to table of contents](#)
5292 
5293 Generated files
5294 ---------------
5295 
5296 - `address.h` gSOAP-specific data binding definitions from address.xsd
5297 - `addressStub.h` C++ data binding definitions
5298 - `addressH.h` Serializers
5299 - `addressC.cpp` Serializers
5300 - `address.xml` Address book data generated by address app
5301 - `graphStub.h` C++ data binding definitions
5302 - `graphH.h` Serializers
5303 - `graphC.cpp` Serializers
5304 - `g.xsd` XSD schema with `g:Graph` complexType
5305 - `g.nsmap` xmlns bindings namespace mapping table
5306 
5307 🔝 [Back to table of contents](#)
5308 
5309 Build steps
5310 -----------
5311 
5312 Building the AddressBook example:
5313 
5314  wsdl2h -g -t addresstypemap.dat address.xsd
5315  soapcpp2 -0 -CS -I../../import -p address address.h
5316  c++ -I../.. address.cpp addressC.cpp -o address -lgsoap++
5317 
5318 Option `-g` produces bindings for global (root) elements in addition to types.
5319 In this case the root element `a:address-book` is bound to `_a__address_book`.
5320 The complexType `a:address` is bound to class `a__address`, which is also the
5321 type of `_a__address_book`. This option is not required, but allows you to use
5322 global element tag names when referring to their serializers, instead of their
5323 type name. Option `-0` removes the SOAP protocol. Options `-C` and `-S`
5324 removes client and server code generation. Option `-p` renames the output
5325 `soap` files to `address` files.
5326 
5327 See the `address.cpp` implementation and [related pages](pages.html).
5328 
5329 The `addresstypemap.dat` file specifies the XML namespace prefix for the
5330 bindings:
5331 
5332  # Bind the address book schema namespace to prefix 'a'
5333 
5334  a = "urn:address-book-example"
5335 
5336  # By default the xsd:dateTime schema type is translated to time_t
5337  # To map xsd:dateTime to struct tm, enable the following line:
5338 
5339  # xsd__dateTime = #import "../../custom/struct_tm.h"
5340 
5341  # ... and compile/link with custom/struct_tm.c
5342 
5343 The DOB field is a `xsd:dateTime`, which is bound to `time_t` by default. To
5344 change this to `struct tm`, enable the import of the `xsd__dateTime` custom
5345 serializer by uncommenting the definition of `xsd__dateTime` in
5346 `addresstypemap.dat`. Then change `soap_dateTime2s` to `soap_xsd__dateTime2s`
5347 in the code.
5348 
5349 Building the graph serialization example:
5350 
5351  soapcpp2 -CS -I../../import -p graph graph.h
5352  c++ -I../.. graph.cpp graphC.cpp -o graph -lgsoap++
5353 
5354 To compile without using the `libgsoap++` library: simply compile
5355 `stdsoap2.cpp` together with the above.
5356 
5357 🔝 [Back to table of contents](#)
5358 
5359 Usage
5360 -----
5361 
5362 To execute the AddressBook example:
5363 
5364  ./address
5365 
5366 To execute the Graph serialization example:
5367 
5368  ./graph
5369