|  | Home | Documentation | README.md Source File updated Tue Aug 22 2017 by Robert van Engelen |

- Main Page
- Related Pages
- Classes
- Files

- File List
- File Members

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