~ubuntu-branches/ubuntu/wily/sip4/wily

« back to all changes in this revision

Viewing changes to doc/html/_sources/directives.txt

  • Committer: Package Import Robot
  • Author(s): Dmitry Shachnev
  • Date: 2014-06-01 12:38:17 UTC
  • mto: (1.5.1)
  • mto: This revision was merged to the branch mainline in revision 21.
  • Revision ID: package-import@ubuntu.com-20140601123817-dbefxopt3wv1ocr9
Tags: upstream-4.16+dfsg
ImportĀ upstreamĀ versionĀ 4.16+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
Directives
2
 
==========
3
 
 
4
 
In this section we describe each of the directives that can be used in
5
 
specification files.  All directives begin with ``%`` as the first
6
 
non-whitespace character in a line.
7
 
 
8
 
Some directives have arguments or contain blocks of code or documentation.  In
9
 
the following descriptions these are shown in *italics*.  Optional arguments
10
 
are enclosed in [*brackets*].
11
 
 
12
 
Some directives are used to specify handwritten code.  Handwritten code must
13
 
not define names that start with the prefix ``sip``.
14
 
 
15
 
 
16
 
Revised Directive Syntax
17
 
------------------------
18
 
 
19
 
.. versionadded:: 4.12
20
 
 
21
 
The directive syntax used in older versions has some problems:
22
 
 
23
 
- it is inconsistent in places
24
 
 
25
 
- it can be problematic to parse
26
 
 
27
 
- it is inflexible.
28
 
 
29
 
SIP v4.12 introduced a revised directive syntax that addresses these problems
30
 
and deprecates the old syntax.  Support for the old syntax will be removed in
31
 
SIP v5.
32
 
 
33
 
The revised syntax is:
34
 
 
35
 
.. parsed-literal::
36
 
 
37
 
    %Directive(arg = value, ...)
38
 
    {
39
 
        %Sub-directive
40
 
        ...
41
 
    };
42
 
 
43
 
A directive may have a number of arguments enclosed in parentheses followed by
44
 
a number of sub-directives enclosed in braces.  Individual arguments and
45
 
sub-directives may be optional.
46
 
 
47
 
Arguments may be specified in any order.  If no arguments are specified then
48
 
the parentheses can be omitted.  If a directive has only one compulsory
49
 
argument then its value may be specified after the directive name and instead
50
 
of the parentheses.
51
 
 
52
 
Sub-directives may be specified in any order.  If no sub-directives are
53
 
specified then the braces can be omitted.
54
 
 
55
 
If a directive is used to specify handwritten code then it may not have
56
 
sub-directives.  In this case the syntax is:
57
 
 
58
 
.. parsed-literal::
59
 
 
60
 
    %Directive(arg = value, ...)
61
 
        *code*
62
 
    %End
63
 
 
64
 
Ordinary C/C++ statements may also have sub-directives.  These will also be
65
 
enclosed in braces.
66
 
 
67
 
The documentation for each directive describes the revised syntax.  The older
68
 
syntax should be used if compatibility with versions of SIP prior to v4.12 is
69
 
required.
70
 
 
71
 
 
72
 
List of Directives
73
 
------------------
74
 
 
75
 
.. directive:: %AccessCode
76
 
 
77
 
.. parsed-literal::
78
 
 
79
 
    %AccessCode
80
 
        *code*
81
 
    %End
82
 
 
83
 
This sub-directive is used in the declaration of an instance of a wrapped class
84
 
or structure, or a pointer to such an instance.  You use it to provide
85
 
handwritten code that overrides the default behaviour.
86
 
 
87
 
For example::
88
 
 
89
 
    class Klass;
90
 
 
91
 
    Klass *klassInstance
92
 
    {
93
 
        %AccessCode
94
 
            // In this contrived example the C++ library we are wrapping
95
 
            // defines klassInstance as Klass ** (which SIP doesn't support) so
96
 
            // we explicitly dereference it.
97
 
            if (klassInstance && *klassInstance)
98
 
                return *klassInstance;
99
 
 
100
 
            // This will get converted to None.
101
 
            return 0;
102
 
        %End
103
 
    };
104
 
 
105
 
.. seealso:: :directive:`%GetCode`, :directive:`%SetCode`
106
 
 
107
 
 
108
 
.. directive:: %API
109
 
 
110
 
.. versionadded:: 4.9
111
 
 
112
 
.. parsed-literal::
113
 
 
114
 
    %API(name = *name*, version = *integer*)
115
 
 
116
 
This directive is used to define an API and set its default version number.  A
117
 
version number must be greater than or equal to 1.
118
 
 
119
 
See :ref:`ref-incompat-apis` for more detail.
120
 
 
121
 
For example::
122
 
 
123
 
    %API(name=PyQt4, version=1)
124
 
 
125
 
 
126
 
.. directive:: %AutoPyName
127
 
 
128
 
.. versionadded:: 4.12
129
 
 
130
 
.. parsed-literal::
131
 
 
132
 
    %AutoPyName(remove_leading = *string*)
133
 
 
134
 
This is a sub-directive of the :directive:`%Module` directive used to specify a
135
 
rule for automatically providing Python names for classes, enums, functions,
136
 
methods, variables and exceptions.  The directive may be specified any number
137
 
of times and each rule will be applied in turn.  Rules will not be applied if
138
 
an item has been given an explicit Python name.
139
 
 
140
 
``remove_leading`` is a string that will be removed from the beginning of any
141
 
C++ or C name.
142
 
 
143
 
For example::
144
 
 
145
 
    %Module PyQt4.QtCore
146
 
    {
147
 
        %AutoPyName(remove_leading="Q")
148
 
    }
149
 
 
150
 
 
151
 
.. directive:: %BIGetBufferCode
152
 
 
153
 
.. parsed-literal::
154
 
 
155
 
    %BIGetBufferCode
156
 
        *code*
157
 
    %End
158
 
 
159
 
This directive (along with :directive:`%BIReleaseBufferCode`) is used to
160
 
specify code that implements the buffer interface of Python v3.  If Python v2
161
 
is being used then this is ignored.
162
 
 
163
 
The following variables are made available to the handwritten code:
164
 
 
165
 
Py_buffer \*sipBuffer
166
 
    This is a pointer to the Python buffer structure that the handwritten code
167
 
    must populate.
168
 
 
169
 
*type* \*sipCpp
170
 
    This is a pointer to the structure or class instance.  Its *type* is a
171
 
    pointer to the structure or class.
172
 
 
173
 
int sipFlags
174
 
    These are the flags that specify what elements of the ``sipBuffer``
175
 
    structure must be populated.
176
 
 
177
 
int sipRes
178
 
    The handwritten code should set this to 0 if there was no error or -1 if
179
 
    there was an error.
180
 
 
181
 
PyObject \*sipSelf
182
 
    This is the Python object that wraps the structure or class instance, i.e.
183
 
    ``self``.
184
 
 
185
 
 
186
 
.. directive:: %BIGetCharBufferCode
187
 
 
188
 
.. parsed-literal::
189
 
 
190
 
    %BIGetCharBufferCode
191
 
        *code*
192
 
    %End
193
 
 
194
 
This directive (along with :directive:`%BIGetReadBufferCode`,
195
 
:directive:`%BIGetSegCountCode` and :directive:`%BIGetWriteBufferCode`) is used
196
 
to specify code that implements the buffer interface of Python v2.  If Python
197
 
v3 is being used then this is ignored.
198
 
 
199
 
The following variables are made available to the handwritten code:
200
 
 
201
 
*type* \*sipCpp
202
 
    This is a pointer to the structure or class instance.  Its *type* is a
203
 
    pointer to the structure or class.
204
 
 
205
 
void \*\*sipPtrPtr
206
 
    This is the pointer used to return the address of the character buffer.
207
 
 
208
 
:c:macro:`SIP_SSIZE_T` sipRes
209
 
    The handwritten code should set this to the length of the character buffer
210
 
    or -1 if there was an error.
211
 
 
212
 
:c:macro:`SIP_SSIZE_T` sipSegment
213
 
    This is the number of the segment of the character buffer.
214
 
 
215
 
PyObject \*sipSelf
216
 
    This is the Python object that wraps the structure or class instance, i.e.
217
 
    ``self``.
218
 
 
219
 
 
220
 
.. directive:: %BIGetReadBufferCode
221
 
 
222
 
.. parsed-literal::
223
 
 
224
 
    %BIGetReadBufferCode
225
 
        *code*
226
 
    %End
227
 
 
228
 
This directive (along with :directive:`%BIGetCharBufferCode`,
229
 
:directive:`%BIGetSegCountCode` and :directive:`%BIGetWriteBufferCode`) is used
230
 
to specify code that implements the buffer interface of Python v2.  If
231
 
Python v3 is being used then this is ignored.
232
 
 
233
 
The following variables are made available to the handwritten code:
234
 
 
235
 
*type* \*sipCpp
236
 
    This is a pointer to the structure or class instance.  Its *type* is a
237
 
    pointer to the structure or class.
238
 
 
239
 
void \*\*sipPtrPtr
240
 
    This is the pointer used to return the address of the read buffer.
241
 
 
242
 
:c:macro:`SIP_SSIZE_T` sipRes
243
 
    The handwritten code should set this to the length of the read buffer or
244
 
    -1 if there was an error.
245
 
 
246
 
:c:macro:`SIP_SSIZE_T` sipSegment
247
 
    This is the number of the segment of the read buffer.
248
 
 
249
 
PyObject \*sipSelf
250
 
    This is the Python object that wraps the structure or class instance, i.e.
251
 
    ``self``.
252
 
 
253
 
 
254
 
.. directive:: %BIGetSegCountCode
255
 
 
256
 
.. parsed-literal::
257
 
 
258
 
    %BIGetSegCountCode
259
 
        *code*
260
 
    %End
261
 
 
262
 
This directive (along with :directive:`%BIGetCharBufferCode`,
263
 
:directive:`%BIGetReadBufferCode` and :directive:`%BIGetWriteBufferCode`) is
264
 
used to specify code that implements the buffer interface of Python v2.  If
265
 
Python v3 is being used then this is ignored.
266
 
 
267
 
The following variables are made available to the handwritten code:
268
 
 
269
 
*type* \*sipCpp
270
 
    This is a pointer to the structure or class instance.  Its *type* is a
271
 
    pointer to the structure or class.
272
 
 
273
 
:c:macro:`SIP_SSIZE_T` \*sipLenPtr
274
 
    This is the pointer used to return the total length in bytes of all
275
 
    segments of the buffer.
276
 
 
277
 
:c:macro:`SIP_SSIZE_T` sipRes
278
 
    The handwritten code should set this to the number of segments that make
279
 
    up the buffer.
280
 
 
281
 
PyObject \*sipSelf
282
 
    This is the Python object that wraps the structure or class instance, i.e.
283
 
    ``self``.
284
 
 
285
 
 
286
 
.. directive:: %BIGetWriteBufferCode
287
 
 
288
 
.. parsed-literal::
289
 
 
290
 
    %BIGetWriteBufferCode
291
 
        *code*
292
 
    %End
293
 
 
294
 
This directive (along with :directive:`%BIGetCharBufferCode`,
295
 
:directive:`%BIGetReadBufferCode` and :directive:`%BIGetSegCountCode` is used
296
 
to specify code that implements the buffer interface of Python v2.  If Python
297
 
v3 is being used then this is ignored.
298
 
 
299
 
The following variables are made available to the handwritten code:
300
 
 
301
 
*type* \*sipCpp
302
 
    This is a pointer to the structure or class instance.  Its *type* is a
303
 
    pointer to the structure or class.
304
 
 
305
 
void \*\*sipPtrPtr
306
 
    This is the pointer used to return the address of the write buffer.
307
 
 
308
 
:c:macro:`SIP_SSIZE_T` sipRes
309
 
    The handwritten code should set this to the length of the write buffer or
310
 
    -1 if there was an error.
311
 
 
312
 
:c:macro:`SIP_SSIZE_T` sipSegment
313
 
    This is the number of the segment of the write buffer.
314
 
 
315
 
PyObject \*sipSelf
316
 
    This is the Python object that wraps the structure or class instance, i.e.
317
 
    ``self``.
318
 
 
319
 
 
320
 
.. directive:: %BIReleaseBufferCode
321
 
 
322
 
.. parsed-literal::
323
 
 
324
 
    %BIReleaseBufferCode
325
 
        *code*
326
 
    %End
327
 
 
328
 
This directive (along with :directive:`%BIGetBufferCode`) is used to specify
329
 
code that implements the buffer interface of Python v3.  If Python v2 is being
330
 
used then this is ignored.
331
 
 
332
 
The following variables are made available to the handwritten code:
333
 
 
334
 
Py_buffer \*sipBuffer
335
 
    This is a pointer to the Python buffer structure.
336
 
 
337
 
*type* \*sipCpp
338
 
    This is a pointer to the structure or class instance.  Its *type* is a
339
 
    pointer to the structure or class.
340
 
 
341
 
PyObject \*sipSelf
342
 
    This is the Python object that wraps the structure or class instance, i.e.
343
 
    ``self``.
344
 
 
345
 
 
346
 
.. directive:: %CModule
347
 
 
348
 
.. deprecated:: 4.12
349
 
    Use the :directive:`%Module` directive with the ``language`` argument set
350
 
    to ``"C"`` instead.
351
 
 
352
 
.. parsed-literal::
353
 
 
354
 
    %CModule *name* [*version*]
355
 
 
356
 
This directive is used to identify that the library being wrapped is a C
357
 
library and to define the name of the module and it's optional version number.
358
 
 
359
 
See the :directive:`%Module` directive for an explanation of the version
360
 
number.
361
 
 
362
 
For example::
363
 
 
364
 
    %CModule dbus 1
365
 
 
366
 
 
367
 
.. directive:: %CompositeModule
368
 
 
369
 
.. parsed-literal::
370
 
 
371
 
    %CompositeModule(name = *dotted-name*)
372
 
    {
373
 
        [:directive:`%Docstring`]
374
 
    };
375
 
 
376
 
A composite module is one that merges a number of related SIP generated
377
 
modules.  For example, a module that merges the modules ``a_mod``, ``b_mod``
378
 
and ``c_mod`` is equivalent to the following pure Python module::
379
 
 
380
 
    from a_mod import *
381
 
    from b_mod import *
382
 
    from c_mod import *
383
 
 
384
 
Clearly the individual modules should not define module-level objects with the
385
 
same name.
386
 
 
387
 
This directive is used to specify the name of a composite module.  Any
388
 
subsequent :directive:`%Module` directive is interpreted as defining a
389
 
component module.
390
 
 
391
 
The optional :directive:`%Docstring` sub-directive is used to specify the
392
 
module's docstring.
393
 
 
394
 
For example::
395
 
 
396
 
    %CompositeModule PyQt4.Qt
397
 
    %Include QtCore/QtCoremod.sip
398
 
    %Include QtGui/QtGuimod.sip
399
 
 
400
 
The main purpose of a composite module is as a programmer convenience as they
401
 
don't have to remember which individual module an object is defined in.
402
 
 
403
 
 
404
 
.. directive:: %ConsolidatedModule
405
 
 
406
 
.. parsed-literal::
407
 
 
408
 
    %ConsolidatedModule(name = *dotted-name*)
409
 
    {
410
 
        [:directive:`%Docstring`]
411
 
    };
412
 
 
413
 
A consolidated module is one that consolidates the wrapper code of a number of
414
 
SIP generated modules (refered to as component modules in this context).
415
 
 
416
 
This directive is used to specify the name of a consolidated module.  Any
417
 
subsequent :directive:`%Module` directive is interpreted as defining a
418
 
component module.
419
 
 
420
 
The optional :directive:`%Docstring` sub-directive is used to specify the
421
 
module's docstring.
422
 
 
423
 
For example::
424
 
 
425
 
    %ConsolidatedModule PyQt4._qt
426
 
    %Include QtCore/QtCoremod.sip
427
 
    %Include QtGui/QtGuimod.sip
428
 
 
429
 
A consolidated module is not intended to be explicitly imported by an
430
 
application.  Instead it is imported by its component modules when they
431
 
themselves are imported.
432
 
 
433
 
Normally the wrapper code is contained in the component module and is linked
434
 
against the corresponding C or C++ library.  The advantage of a consolidated
435
 
module is that it allows all of the wrapped C or C++ libraries to be linked
436
 
against a single module.  If the linking is done statically then deployment of
437
 
generated modules can be greatly simplified.
438
 
 
439
 
It follows that a component module can be built in one of two ways, as a
440
 
normal standalone module, or as a component of a consolidated module.  When
441
 
building as a component the ``-p`` command line option should be used to
442
 
specify the name of the consolidated module.
443
 
 
444
 
 
445
 
.. directive:: %ConvertFromTypeCode
446
 
 
447
 
.. parsed-literal::
448
 
 
449
 
    %ConvertFromTypeCode
450
 
        *code*
451
 
    %End
452
 
 
453
 
This directive is used as part of the :directive:`%MappedType` directive (when
454
 
it is required) or of a class specification (when it is optional) to specify
455
 
the handwritten code that converts an instance of a C/C++ type to a Python
456
 
object.
457
 
 
458
 
If used as part of a class specification then instances of the class will be
459
 
automatically converted to the Python object, even though the class itself has
460
 
been wrapped.  This behaviour can be changed on a temporary basis from an
461
 
application by calling the :func:`sip.enableautoconversion` function, or from
462
 
handwritten code by calling the :c:func:`sipEnableAutoconversion` function.
463
 
 
464
 
The following variables are made available to the handwritten code:
465
 
 
466
 
*type* \*sipCpp
467
 
    This is a pointer to the C/C++ instance to be converted.  It will never be
468
 
    zero as the conversion from zero to ``Py_None`` is handled before the
469
 
    handwritten code is called.
470
 
 
471
 
PyObject \*sipTransferObj
472
 
    This specifies any desired ownership changes to the returned object.  If it
473
 
    is ``NULL`` then the ownership should be left unchanged.  If it is
474
 
    ``Py_None`` then ownership should be transferred to Python.  Otherwise
475
 
    ownership should be transferred to C/C++ and the returned object associated
476
 
    with *sipTransferObj*.  The code can choose to interpret these changes in
477
 
    any way.  For example, if the code is converting a C++ container of wrapped
478
 
    classes to a Python list it is likely that the ownership changes should be
479
 
    made to each element of the list.
480
 
 
481
 
The handwritten code must explicitly return a ``PyObject *``.  If there was an
482
 
error then a Python exception must be raised and ``NULL`` returned.
483
 
 
484
 
The following example converts a ``QList<QWidget *>`` instance to a Python
485
 
list of ``QWidget`` instances::
486
 
 
487
 
    %ConvertFromTypeCode
488
 
        PyObject *l;
489
 
 
490
 
        // Create the Python list of the correct length.
491
 
        if ((l = PyList_New(sipCpp->size())) == NULL)
492
 
            return NULL;
493
 
 
494
 
        // Go through each element in the C++ instance and convert it to a
495
 
        // wrapped QWidget.
496
 
        for (int i = 0; i < sipCpp->size(); ++i)
497
 
        {
498
 
            QWidget *w = sipCpp->at(i);
499
 
            PyObject *wobj;
500
 
 
501
 
            // Get the Python wrapper for the QWidget instance, creating a new
502
 
            // one if necessary, and handle any ownership transfer.
503
 
            if ((wobj = sipConvertFromType(w, sipType_QWidget, sipTransferObj)) == NULL)
504
 
            {
505
 
                // There was an error so garbage collect the Python list.
506
 
                Py_DECREF(l);
507
 
                return NULL;
508
 
            }
509
 
 
510
 
            // Add the wrapper to the list.
511
 
            PyList_SET_ITEM(l, i, wobj);
512
 
        }
513
 
 
514
 
        // Return the Python list.
515
 
        return l;
516
 
    %End
517
 
 
518
 
 
519
 
.. directive:: %ConvertToSubClassCode
520
 
 
521
 
.. parsed-literal::
522
 
 
523
 
    %ConvertToSubClassCode
524
 
        *code*
525
 
    %End
526
 
 
527
 
When SIP needs to wrap a C++ class instance it first checks to make sure it
528
 
hasn't already done so.  If it has then it just returns a new reference to the
529
 
corresponding Python object.  Otherwise it creates a new Python object of the
530
 
appropriate type.  In C++ a function may be defined to return an instance of a
531
 
certain class, but can often return a sub-class instead.
532
 
 
533
 
This directive is used to specify handwritten code that exploits any available
534
 
real-time type information (RTTI) to see if there is a more specific Python
535
 
type that can be used when wrapping the C++ instance.  The RTTI may be
536
 
provided by the compiler or by the C++ instance itself.
537
 
 
538
 
The directive is included in the specification of one of the classes that the
539
 
handwritten code handles the type conversion for.  It doesn't matter which
540
 
one, but a sensible choice would be the one at the root of that class
541
 
hierarchy in the module.
542
 
 
543
 
Note that if a class hierarchy extends over a number of modules then this
544
 
directive should be used in each of those modules to handle the part of the
545
 
hierarchy defined in that module.  SIP will ensure that the different pieces
546
 
of code are called in the right order to determine the most specific Python
547
 
type to use.
548
 
 
549
 
The following variables are made available to the handwritten code:
550
 
 
551
 
*type* \*sipCpp
552
 
    This is a pointer to the C++ class instance.
553
 
 
554
 
void \*\*sipCppRet
555
 
    When the sub-class is derived from more than one super-class then it is
556
 
    possible that the C++ address of the instance as the sub-class is
557
 
    different to that of the super-class.  If so, then this must be set to the
558
 
    C++ address of the instance when cast (usually using ``static_cast``)
559
 
    from the super-class to the sub-class.
560
 
 
561
 
const sipTypeDef \*sipType
562
 
    The handwritten code must set this to the SIP generated type structure
563
 
    that corresponds to the class instance.  (The type structure for class
564
 
    ``Klass`` is ``sipType_Klass``.)  If the RTTI of the class instance isn't
565
 
    recognised then ``sipType`` must be set to ``NULL``.  The code doesn't
566
 
    have to recognise the exact class, only the most specific sub-class that
567
 
    it can.
568
 
 
569
 
    The code may also set the value to a type that is apparently unrelated to
570
 
    the requested type.  If this happens then the whole conversion process is
571
 
    started again using the new type as the requested type.  This is typically
572
 
    used to deal with classes that have more than one super-class that are
573
 
    subject to this conversion process.  It allows the code for one super-class
574
 
    to switch to the code for another (more appropriate) super-class.
575
 
 
576
 
sipWrapperType \*sipClass
577
 
    .. deprecated:: 4.8
578
 
        Use ``sipType`` instead.
579
 
 
580
 
    The handwritten code must set this to the SIP generated Python type object
581
 
    that corresponds to the class instance.  (The type object for class
582
 
    ``Klass`` is ``sipClass_Klass``.)  If the RTTI of the class instance isn't
583
 
    recognised then ``sipClass`` must be set to ``NULL``.  The code doesn't
584
 
    have to recognise the exact class, only the most specific sub-class that
585
 
    it can.
586
 
 
587
 
The handwritten code must not explicitly return.
588
 
 
589
 
The following example shows the sub-class conversion code for ``QEvent`` based
590
 
class hierarchy in PyQt::
591
 
 
592
 
    class QEvent
593
 
    {
594
 
    %ConvertToSubClassCode
595
 
        // QEvent sub-classes provide a unique type ID.
596
 
        switch (sipCpp->type())
597
 
        {
598
 
        case QEvent::Timer:
599
 
            sipType = sipType_QTimerEvent;
600
 
            break;
601
 
 
602
 
        case QEvent::KeyPress:
603
 
        case QEvent::KeyRelease:
604
 
            sipType = sipType_QKeyEvent;
605
 
            break;
606
 
 
607
 
        // Skip the remaining event types to keep the example short.
608
 
 
609
 
        default:
610
 
            // We don't recognise the type.
611
 
            sipType = NULL;
612
 
        }
613
 
    %End
614
 
 
615
 
        // The rest of the class specification.
616
 
 
617
 
    };
618
 
 
619
 
 
620
 
.. directive:: %ConvertToTypeCode
621
 
 
622
 
.. parsed-literal::
623
 
 
624
 
    %ConvertToTypeCode
625
 
        *code*
626
 
    %End
627
 
 
628
 
This directive is used to specify the handwritten code that converts a Python
629
 
object to a mapped type instance and to handle any ownership transfers.  It is
630
 
used as part of the :directive:`%MappedType` directive and as part of a class
631
 
specification.  The code is also called to determine if the Python object is of
632
 
the correct type prior to conversion.
633
 
 
634
 
When used as part of a class specification it can automatically convert
635
 
additional types of Python object.  For example, PyQt uses it in the
636
 
specification of the ``QString`` class to allow Python string objects and
637
 
unicode objects to be used wherever ``QString`` instances are expected.
638
 
 
639
 
The following variables are made available to the handwritten code:
640
 
 
641
 
int \*sipIsErr
642
 
    If this is ``NULL`` then the code is being asked to check the type of the
643
 
    Python object.  The check must not have any side effects.  Otherwise the
644
 
    code is being asked to convert the Python object and a non-zero value
645
 
    should be returned through this pointer if an error occurred during the
646
 
    conversion.
647
 
 
648
 
PyObject \*sipPy
649
 
    This is the Python object to be converted.
650
 
 
651
 
*type* \*\*sipCppPtr
652
 
    This is a pointer through which the address of the mapped type instance (or
653
 
    zero if appropriate) is returned.  Its value is undefined if ``sipIsErr``
654
 
    is ``NULL``.
655
 
 
656
 
PyObject \*sipTransferObj
657
 
    This specifies any desired ownership changes to *sipPy*.  If it is ``NULL``
658
 
    then the ownership should be left unchanged.  If it is ``Py_None`` then
659
 
    ownership should be transferred to Python.  Otherwise ownership should be
660
 
    transferred to C/C++ and *sipPy* associated with *sipTransferObj*.  The
661
 
    code can choose to interpret these changes in any way.
662
 
 
663
 
The handwritten code must explicitly return an ``int`` the meaning of which
664
 
depends on the value of ``sipIsErr``.
665
 
 
666
 
If ``sipIsErr`` is ``NULL`` then a non-zero value is returned if the Python
667
 
object has a type that can be converted to the mapped type.  Otherwise zero is
668
 
returned.
669
 
 
670
 
If ``sipIsErr`` is not ``NULL`` then a combination of the following flags is
671
 
returned.
672
 
 
673
 
        - :c:macro:`SIP_TEMPORARY` is set to indicate that the returned
674
 
          instance is a temporary and should be released to avoid a memory
675
 
          leak.
676
 
 
677
 
        - :c:macro:`SIP_DERIVED_CLASS` is set to indicate that the type of the
678
 
          returned instance is a derived class.  See
679
 
          :ref:`ref-derived-classes`.
680
 
 
681
 
The following example converts a Python list of ``QPoint`` instances to a
682
 
``QList<QPoint>`` instance::
683
 
 
684
 
    %ConvertToTypeCode
685
 
        // See if we are just being asked to check the type of the Python
686
 
        // object.
687
 
        if (!sipIsErr)
688
 
        {
689
 
            // Checking whether or not None has been passed instead of a list
690
 
            // has already been done.
691
 
            if (!PyList_Check(sipPy))
692
 
                return 0;
693
 
 
694
 
            // Check the type of each element.  We specify SIP_NOT_NONE to
695
 
            // disallow None because it is a list of QPoint, not of a pointer
696
 
            // to a QPoint, so None isn't appropriate.
697
 
            for (int i = 0; i < PyList_GET_SIZE(sipPy); ++i)
698
 
                if (!sipCanConvertToType(PyList_GET_ITEM(sipPy, i),
699
 
                                         sipType_QPoint, SIP_NOT_NONE))
700
 
                    return 0;
701
 
 
702
 
            // The type is valid.
703
 
            return 1;
704
 
        }
705
 
 
706
 
        // Create the instance on the heap.
707
 
        QList<QPoint> *ql = new QList<QPoint>;
708
 
 
709
 
        for (int i = 0; i < PyList_GET_SIZE(sipPy); ++i)
710
 
        {
711
 
            QPoint *qp;
712
 
            int state;
713
 
 
714
 
            // Get the address of the element's C++ instance.  Note that, in
715
 
            // this case, we don't apply any ownership changes to the list
716
 
            // elements, only to the list itself.
717
 
            qp = reinterpret_cast<QPoint *>(sipConvertToType(
718
 
                                                    PyList_GET_ITEM(sipPy, i),
719
 
                                                    sipType_QPoint, 0,
720
 
                                                    SIP_NOT_NONE,
721
 
                                                    &state, sipIsErr));
722
 
 
723
 
            // Deal with any errors.
724
 
            if (*sipIsErr)
725
 
            {
726
 
                sipReleaseType(qp, sipType_QPoint, state);
727
 
 
728
 
                // Tidy up.
729
 
                delete ql;
730
 
 
731
 
                // There is no temporary instance.
732
 
                return 0;
733
 
            }
734
 
 
735
 
            ql->append(*qp);
736
 
 
737
 
            // A copy of the QPoint was appended to the list so we no longer
738
 
            // need it.  It may be a temporary instance that should be
739
 
            // destroyed, or a wrapped instance that should not be destroyed.
740
 
            // sipReleaseType() will do the right thing.
741
 
            sipReleaseType(qp, sipType_QPoint, state);
742
 
        }
743
 
 
744
 
        // Return the instance.
745
 
        *sipCppPtr = ql;
746
 
 
747
 
        // The instance should be regarded as temporary (and be destroyed as
748
 
        // soon as it has been used) unless it has been transferred from
749
 
        // Python.  sipGetState() is a convenience function that implements
750
 
        // this common transfer behaviour.
751
 
        return sipGetState(sipTransferObj);
752
 
    %End
753
 
 
754
 
When used in a class specification the handwritten code replaces the code that
755
 
would normally be automatically generated.  This means that the handwritten
756
 
code must also handle instances of the class itself and not just the additional
757
 
types that are being supported.  This should be done by making calls to
758
 
:c:func:`sipCanConvertToType()` to check the object type and
759
 
:c:func:`sipConvertToType()` to convert the object.  The
760
 
:c:macro:`SIP_NO_CONVERTORS` flag *must* be passed to both these functions to
761
 
prevent recursive calls to the handwritten code.
762
 
 
763
 
 
764
 
.. directive:: %Copying
765
 
 
766
 
.. parsed-literal::
767
 
 
768
 
    %Copying
769
 
        *text*
770
 
    %End
771
 
 
772
 
This directive is used to specify some arbitrary text that will be included at
773
 
the start of all source files generated by SIP.  It is normally used to include
774
 
copyright and licensing terms.
775
 
 
776
 
For example::
777
 
 
778
 
    %Copying
779
 
    Copyright (c) 2014 Riverbank Computing Limited
780
 
    %End
781
 
 
782
 
 
783
 
.. directive:: %DefaultDocstringFormat
784
 
 
785
 
.. versionadded:: 4.13
786
 
 
787
 
.. parsed-literal::
788
 
 
789
 
    %DefaultDocstringFormat(name = ["raw" | "deindented"])
790
 
 
791
 
This directive is used to specify the default formatting of docstrings, i.e.
792
 
when the :directive:`%Docstring` directive does not specify an explicit format.
793
 
 
794
 
See the :directive:`%Docstring` directive for an explanation of the different
795
 
formats.  If the directive is not specified then the default format used is
796
 
``"raw"``.
797
 
 
798
 
For example::
799
 
 
800
 
    %DefaultDocstringFormat "deindented"
801
 
 
802
 
 
803
 
.. directive:: %DefaultEncoding
804
 
 
805
 
.. parsed-literal::
806
 
 
807
 
    %DefaultEncoding(name = ["ASCII" | "Latin-1" | "UTF-8" | "None"])
808
 
 
809
 
This directive is used to specify the default encoding used for ``char``,
810
 
``const char``, ``char *`` or ``const char *`` values.  An encoding of
811
 
``"None"`` means that the value is unencoded.  The default can be overridden
812
 
for a particular value using the :aanno:`Encoding` annotation.
813
 
    
814
 
If the directive is not specified then the default encoding of the last
815
 
imported module is used, if any.
816
 
 
817
 
For example::
818
 
 
819
 
    %DefaultEncoding "Latin-1"
820
 
 
821
 
 
822
 
.. directive:: %DefaultMetatype
823
 
 
824
 
.. parsed-literal::
825
 
 
826
 
    %DefaultMetatype(name = *dotted-name*)
827
 
 
828
 
This directive is used to specify the Python type that should be used as the
829
 
meta-type for any C/C++ data type defined in the same module, and by importing
830
 
modules, that doesn't have an explicit meta-type.
831
 
 
832
 
If this is not specified then ``sip.wrappertype`` is used.
833
 
 
834
 
You can also use the :canno:`Metatype` class annotation to specify the
835
 
meta-type used by a particular C/C++ type.
836
 
 
837
 
See the section :ref:`ref-types-metatypes` for more details.
838
 
 
839
 
For example::
840
 
 
841
 
    %DefaultMetatype PyQt4.QtCore.pyqtWrapperType
842
 
 
843
 
 
844
 
.. directive:: %DefaultSupertype
845
 
 
846
 
.. parsed-literal::
847
 
 
848
 
    %DefaultSupertype(name = *dotted-name*)
849
 
 
850
 
This directive is used to specify the Python type that should be used as the
851
 
super-type for any C/C++ data type defined in the same module that doesn't have
852
 
an explicit super-type.
853
 
 
854
 
If this is not specified then ``sip.wrapper`` is used.
855
 
 
856
 
You can also use the :canno:`Supertype` class annotation to specify the
857
 
super-type used by a particular C/C++ type.
858
 
 
859
 
See the section :ref:`ref-types-metatypes` for more details.
860
 
 
861
 
For example::
862
 
 
863
 
    %DefaultSupertype sip.simplewrapper
864
 
 
865
 
 
866
 
.. directive:: %Doc
867
 
 
868
 
.. deprecated:: 4.12
869
 
    Use the :directive:`%Extract` directive instead.
870
 
 
871
 
.. parsed-literal::
872
 
 
873
 
    %Doc
874
 
        *text*
875
 
    %End
876
 
 
877
 
This directive is used to specify some arbitrary text that will be extracted
878
 
by SIP when the ``-d`` command line option is used.  The directive can be
879
 
specified any number of times and SIP will concatenate all the separate pieces
880
 
of text in the order that it sees them.
881
 
 
882
 
Documentation that is specified using this directive is local to the module in
883
 
which it appears.  It is ignored by modules that :directive:`%Import` it.  Use
884
 
the :directive:`%ExportedDoc` directive for documentation that should be
885
 
included by all modules that :directive:`%Import` this one.
886
 
 
887
 
For example::
888
 
 
889
 
    %Doc
890
 
    <h1>An Example</h1>
891
 
    <p>
892
 
    This fragment of documentation is HTML and is local to the module in
893
 
    which it is defined.
894
 
    </p>
895
 
    %End
896
 
 
897
 
 
898
 
.. directive:: %Docstring
899
 
 
900
 
.. versionadded:: 4.10
901
 
 
902
 
.. parsed-literal::
903
 
 
904
 
    %Docstring(format = ["raw" | "deindented"])
905
 
        *text*
906
 
    %End
907
 
 
908
 
This directive is used to specify explicit docstrings for modules, classes,
909
 
functions, methods and properties.
910
 
 
911
 
The docstring of a class is made up of the docstring specified for the class
912
 
itself, with the docstrings specified for each contructor appended.
913
 
 
914
 
The docstring of a function or method is made up of the concatenated docstrings
915
 
specified for each of the overloads.
916
 
 
917
 
Specifying an explicit docstring will prevent SIP from generating an automatic
918
 
docstring that describes the Python signature of a function or method overload.
919
 
This means that SIP will generate less informative exceptions (i.e. without a
920
 
full signature) when it fails to match a set of arguments to any function or
921
 
method overload.
922
 
 
923
 
.. versionadded:: 4.13
924
 
 
925
 
The format may either be ``"raw"`` or ``"deindented"``.  If it is not specified
926
 
then the value specified by any :directive:`%DefaultDocstringFormat` directive
927
 
is used.
928
 
 
929
 
If the format is ``"raw"`` then the docstring is used as it appears in the
930
 
specification file.
931
 
 
932
 
If the format is ``"deindented"`` then any leading spaces common to all
933
 
non-blank lines of the docstring are removed.
934
 
 
935
 
For example::
936
 
 
937
 
    class Klass
938
 
    {
939
 
    %Docstring
940
 
    This will be at the start of the class's docstring.
941
 
    %End
942
 
 
943
 
    public:
944
 
        Klass();
945
 
    %Docstring deindented
946
 
        This will be appended to the class's docstring and will not be indented.
947
 
 
948
 
            This will be indented by four spaces.
949
 
    %End
950
 
    };
951
 
 
952
 
 
953
 
.. directive:: %End
954
 
 
955
 
This isn't a directive in itself, but is used to terminate a number of
956
 
directives that allow a block of handwritten code or text to be specified.
957
 
 
958
 
 
959
 
.. directive:: %Exception
960
 
 
961
 
.. parsed-literal::
962
 
 
963
 
    %Exception *name* [(*base-exception*)]
964
 
    {
965
 
        [:directive:`%TypeHeaderCode`]
966
 
        :directive:`%RaiseCode`
967
 
    };
968
 
 
969
 
This directive is used to define new Python exceptions, or to provide a stub
970
 
for existing Python exceptions.  It allows handwritten code to be provided
971
 
that implements the translation between C++ exceptions and Python exceptions.
972
 
The arguments to ``throw ()`` specifiers must either be names of classes or the
973
 
names of Python exceptions defined by this directive.
974
 
 
975
 
*name* is the name of the exception.
976
 
 
977
 
*base-exception* is the optional base exception.  This may be either one of
978
 
the standard Python exceptions or one defined with a previous
979
 
:directive:`%Exception` directive.
980
 
 
981
 
The optional :directive:`%TypeHeaderCode` sub-directive is used to specify any
982
 
external interface to the exception being defined.
983
 
 
984
 
The :directive:`%RaiseCode` sub-directive is used to specify the handwritten
985
 
code that converts a reference to the C++ exception to the Python exception.
986
 
 
987
 
For example::
988
 
 
989
 
    %Exception std::exception(SIP_Exception) /PyName=StdException/
990
 
    {
991
 
    %TypeHeaderCode
992
 
    #include <exception>
993
 
    %End
994
 
    %RaiseCode
995
 
        const char *detail = sipExceptionRef.what();
996
 
 
997
 
        SIP_BLOCK_THREADS
998
 
        PyErr_SetString(sipException_std_exception, detail);
999
 
        SIP_UNBLOCK_THREADS
1000
 
    %End
1001
 
    };
1002
 
 
1003
 
In this example we map the standard C++ exception to a new Python exception.
1004
 
The new exception is called ``StdException`` and is derived from the standard
1005
 
Python exception ``Exception``.
1006
 
 
1007
 
An exception may be annotated with :xanno:`Default` to specify that it should
1008
 
be caught by default if there is no ``throw`` clause.
1009
 
 
1010
 
 
1011
 
.. directive:: %ExportedDoc
1012
 
 
1013
 
.. deprecated:: 4.12
1014
 
    Use the :directive:`%Extract` directive instead.
1015
 
 
1016
 
.. parsed-literal::
1017
 
 
1018
 
    %ExportedDoc
1019
 
        *text*
1020
 
    %End
1021
 
 
1022
 
This directive is used to specify some arbitrary text that will be extracted
1023
 
by SIP when the ``-d`` command line option is used.  The directive can be
1024
 
specified any number of times and SIP will concatenate all the separate pieces
1025
 
of text in the order that it sees them.
1026
 
 
1027
 
Documentation that is specified using this directive will also be included by
1028
 
modules that :directive:`%Import` it.
1029
 
 
1030
 
For example::
1031
 
 
1032
 
    %ExportedDoc
1033
 
    ==========
1034
 
    An Example
1035
 
    ==========
1036
 
    
1037
 
    This fragment of documentation is reStructuredText and will appear in the
1038
 
    module in which it is defined and all modules that %Import it.
1039
 
    %End
1040
 
 
1041
 
 
1042
 
.. directive:: %ExportedHeaderCode
1043
 
 
1044
 
.. parsed-literal::
1045
 
 
1046
 
    %ExportedHeaderCode
1047
 
        *code*
1048
 
    %End
1049
 
 
1050
 
This directive is used to specify handwritten code, typically the declarations
1051
 
of types, that is placed in a header file that is included by all generated
1052
 
code for all modules.  It should not include function declarations because
1053
 
Python modules should not explicitly call functions in another Python module.
1054
 
 
1055
 
.. seealso:: :directive:`%ModuleCode`, :directive:`%ModuleHeaderCode`
1056
 
 
1057
 
 
1058
 
.. directive:: %Extract
1059
 
 
1060
 
.. versionadded:: 4.12
1061
 
 
1062
 
.. parsed-literal::
1063
 
 
1064
 
    %Extract(id = *name* [, order = *integer*])
1065
 
        *text*
1066
 
    %End
1067
 
 
1068
 
This directive is used to specify part of an extract.  An extract is a
1069
 
collection of arbitrary text specified as one or more parts each having the
1070
 
same ``id``.  SIP places no interpretation on an identifier, or on the
1071
 
contents of the extract.  Extracts may be used for any purpose, e.g.
1072
 
documentation, tests etc.
1073
 
 
1074
 
The part's optional ``order`` determines its position relative to the extract's
1075
 
other parts.  If the order is not specified then the part is appended to the
1076
 
extract.
1077
 
 
1078
 
An extract is written to a file using the :option:`-X <sip -X>` command line
1079
 
option.
1080
 
 
1081
 
For example::
1082
 
 
1083
 
    %Extract example
1084
 
    This will be the last line because there is no explicit order.
1085
 
    %End
1086
 
 
1087
 
    %Extract(id=example, order=20)
1088
 
    This will be the second line.
1089
 
    %End
1090
 
 
1091
 
    %Extract(id=example, order=10)
1092
 
    This will be the first line.
1093
 
    %End
1094
 
 
1095
 
 
1096
 
.. directive:: %Feature
1097
 
 
1098
 
.. parsed-literal::
1099
 
 
1100
 
    %Feature(name = *name*)
1101
 
 
1102
 
This directive is used to declare a feature.  Features (along with
1103
 
:directive:`%Platforms` and :directive:`%Timeline`) are used by the
1104
 
:directive:`%If` directive to control whether or not parts of a specification
1105
 
are processed or ignored.
1106
 
 
1107
 
Features are mutually independent of each other - any combination of features
1108
 
may be enabled or disable.  By default all features are enabled.  The
1109
 
:option:`-x <sip -x>` command line option is used to disable a feature.
1110
 
 
1111
 
If a feature is enabled then SIP will automatically generate a corresponding C
1112
 
preprocessor symbol for use by handwritten code.  The symbol is the name of
1113
 
the feature prefixed by ``SIP_FEATURE_``.
1114
 
 
1115
 
For example::
1116
 
 
1117
 
    %Feature FOO_SUPPORT
1118
 
 
1119
 
    %If (FOO_SUPPORT)
1120
 
    void foo();
1121
 
    %End
1122
 
 
1123
 
 
1124
 
.. directive:: %FinalisationCode
1125
 
 
1126
 
.. versionadded:: 4.15
1127
 
 
1128
 
.. parsed-literal::
1129
 
 
1130
 
    %FinalisationCode
1131
 
        *code*
1132
 
    %End
1133
 
 
1134
 
This directive is used to specify handwritten code that is executed one the
1135
 
instance of a wrapped class has been created.  The handwritten code is passed a
1136
 
dictionary of any remaining keyword arguments.  It must explicitly return an
1137
 
integer result which should be ``0`` if there was no error.  If an error
1138
 
occurred then ``-1`` should be returned and a Python exception raised.
1139
 
 
1140
 
The following variables are made available to the handwritten code:
1141
 
 
1142
 
PyObject \*sipSelf
1143
 
    This is the Python object that wraps the structure or class instance, i.e.
1144
 
    ``self``.
1145
 
 
1146
 
*type* \*sipCpp
1147
 
    This is a pointer to the structure or class instance.  Its *type* is a
1148
 
    pointer to the structure or class.
1149
 
 
1150
 
PyObject \*sipKwds
1151
 
    This is an optional dictionary of unused keyword arguments.  It may be
1152
 
    ``NULL`` or refer to an empty dictionary.  If the handwritten code handles
1153
 
    any of the arguments then, if ``sipUnused`` is ``NULL``, those arguments
1154
 
    must be removed from the dictionary.  If ``sipUnused`` is not ``NULL`` then
1155
 
    the ``sipKwds`` dictionary must not be updated.  Instead a new dictionary
1156
 
    must be created that contains any remaining unused keyword arguments and
1157
 
    the address of the new dictionary returned via ``sipUnused``.  This rather
1158
 
    complicated API ensures that new dictionaries are created only when
1159
 
    necessary.
1160
 
 
1161
 
PyObject \*\*sipUnused
1162
 
    This is an optional pointer to where the handwritten code should save the
1163
 
    address of any new dictionary of unused keyword arguments that it creates.
1164
 
    If it is ``NULL`` then the handwritten code is allowed to update the
1165
 
    ``sipKwds`` dictionary.
1166
 
 
1167
 
 
1168
 
.. directive:: %GCClearCode
1169
 
 
1170
 
.. parsed-literal::
1171
 
 
1172
 
    %GCClearCode
1173
 
        *code*
1174
 
    %End
1175
 
 
1176
 
Python has a cyclic garbage collector which can identify and release unneeded
1177
 
objects even when their reference counts are not zero.  If a wrapped C
1178
 
structure or C++ class keeps its own reference to a Python object then, if the
1179
 
garbage collector is to do its job, it needs to provide some handwritten code
1180
 
to traverse and potentially clear those embedded references.
1181
 
 
1182
 
See the section `Supporting Cyclic Garbage Collection
1183
 
<http://docs.python.org/3/c-api/gcsupport.html>`__ in the Python documentation
1184
 
for the details.
1185
 
 
1186
 
This directive is used to specify the code that clears any embedded references.
1187
 
(See :directive:`%GCTraverseCode` for specifying the code that traverses any
1188
 
embedded references.)
1189
 
 
1190
 
The following variables are made available to the handwritten code:
1191
 
 
1192
 
*type* \*sipCpp
1193
 
    This is a pointer to the structure or class instance.  Its *type* is a
1194
 
    pointer to the structure or class.
1195
 
 
1196
 
int sipRes
1197
 
    The handwritten code should set this to the result to be returned.
1198
 
 
1199
 
The following simplified example is taken from PyQt.  The ``QCustomEvent``
1200
 
class allows arbitary data to be attached to the event.  In PyQt this data is
1201
 
always a Python object and so should be handled by the garbage collector::
1202
 
 
1203
 
    %GCClearCode
1204
 
        PyObject *obj;
1205
 
 
1206
 
        // Get the object.
1207
 
        obj = reinterpret_cast<PyObject *>(sipCpp->data());
1208
 
 
1209
 
        // Clear the pointer.
1210
 
        sipCpp->setData(0);
1211
 
 
1212
 
        // Clear the reference.
1213
 
        Py_XDECREF(obj);
1214
 
 
1215
 
        // Report no error.
1216
 
        sipRes = 0;
1217
 
    %End
1218
 
 
1219
 
 
1220
 
.. directive:: %GCTraverseCode
1221
 
 
1222
 
.. parsed-literal::
1223
 
 
1224
 
    %GCTraverseCode
1225
 
        *code*
1226
 
    %End
1227
 
 
1228
 
This directive is used to specify the code that traverses any embedded
1229
 
references for Python's cyclic garbage collector.  (See
1230
 
:directive:`%GCClearCode` for a full explanation.)
1231
 
 
1232
 
The following variables are made available to the handwritten code:
1233
 
 
1234
 
*type* \*sipCpp
1235
 
    This is a pointer to the structure or class instance.  Its *type* is a
1236
 
    pointer to the structure or class.
1237
 
 
1238
 
visitproc sipVisit
1239
 
    This is the visit function provided by the garbage collector.
1240
 
 
1241
 
void \*sipArg
1242
 
    This is the argument to the visit function provided by the garbage
1243
 
    collector.
1244
 
 
1245
 
int sipRes
1246
 
    The handwritten code should set this to the result to be returned.
1247
 
 
1248
 
The following simplified example is taken from PyQt's ``QCustomEvent`` class::
1249
 
 
1250
 
    %GCTraverseCode
1251
 
        PyObject *obj;
1252
 
 
1253
 
        // Get the object.
1254
 
        obj = reinterpret_cast<PyObject *>(sipCpp->data());
1255
 
 
1256
 
        // Call the visit function if there was an object.
1257
 
        if (obj)
1258
 
            sipRes = sipVisit(obj, sipArg);
1259
 
        else
1260
 
            sipRes = 0;
1261
 
    %End
1262
 
 
1263
 
 
1264
 
.. directive:: %GetCode
1265
 
 
1266
 
.. parsed-literal::
1267
 
 
1268
 
    %GetCode
1269
 
        *code*
1270
 
    %End
1271
 
 
1272
 
This sub-directive is used in the declaration of a C++ class variable or C
1273
 
structure member to specify handwritten code to convert it to a Python object.
1274
 
It is usually used to handle types that SIP cannot deal with automatically.
1275
 
 
1276
 
The following variables are made available to the handwritten code:
1277
 
 
1278
 
*type* \*sipCpp
1279
 
    This is a pointer to the structure or class instance.  Its *type* is a
1280
 
    pointer to the structure or class.  It is not made available if the
1281
 
    variable being wrapped is a static class variable.
1282
 
 
1283
 
PyObject \*sipPy
1284
 
    The handwritten code must set this to the Python representation of the
1285
 
    class variable or structure member.  If there is an error then the code
1286
 
    must raise an exception and set this to ``NULL``.
1287
 
 
1288
 
PyObject \*sipPyType
1289
 
    If the variable being wrapped is a static class variable then this is the
1290
 
    Python type object of the class from which the variable was referenced
1291
 
    (*not* the class in which it is defined).  It may be safely cast to a
1292
 
    PyTypeObject \* or a sipWrapperType \*.
1293
 
 
1294
 
For example::
1295
 
 
1296
 
    struct Entity
1297
 
    {
1298
 
        /*
1299
 
         * In this contrived example the C library we are wrapping actually
1300
 
         * defines this as char buffer[100] which SIP cannot handle
1301
 
         * automatically.
1302
 
         */
1303
 
        char *buffer
1304
 
        {
1305
 
            %GetCode
1306
 
                sipPy = PyString_FromStringAndSize(sipCpp->buffer, 100);
1307
 
            %End
1308
 
 
1309
 
            %SetCode
1310
 
                char *ptr;
1311
 
                int length;
1312
 
 
1313
 
                if (PyString_AsStringAndSize(sipPy, &ptr, &length) == -1)
1314
 
                {
1315
 
                    sipErr = 1;
1316
 
                }
1317
 
                else if (length != 100)
1318
 
                {
1319
 
                    /*
1320
 
                     * Raise an exception because the length isn't exactly
1321
 
                     * right.
1322
 
                     */
1323
 
 
1324
 
                    PyErr_SetString(PyExc_ValueError,
1325
 
                            "an Entity.buffer must be exactly 100 bytes");
1326
 
                    sipErr = 1;
1327
 
                }
1328
 
                else
1329
 
                {
1330
 
                    memcpy(sipCpp->buffer, ptr, 100);
1331
 
                }
1332
 
            %End
1333
 
        };
1334
 
    }
1335
 
 
1336
 
.. seealso:: :directive:`%AccessCode`, :directive:`%SetCode`
1337
 
 
1338
 
 
1339
 
.. directive:: %If
1340
 
 
1341
 
.. parsed-literal::
1342
 
 
1343
 
    %If (*expression*)
1344
 
        *specification*
1345
 
    %End
1346
 
 
1347
 
where
1348
 
 
1349
 
.. parsed-literal::
1350
 
 
1351
 
    *expression* ::= [*ored-qualifiers* | *range*]
1352
 
 
1353
 
    *ored-qualifiers* ::= [*qualifier* | *qualifier* **||** *ored-qualifiers*]
1354
 
 
1355
 
    *qualifier* ::= [**!**] [*feature* | *platform*]
1356
 
 
1357
 
    *range* ::= [*version*] **-** [*version*]
1358
 
 
1359
 
This directive is used in conjunction with features (see
1360
 
:directive:`%Feature`), platforms (see :directive:`%Platforms`) and versions
1361
 
(see :directive:`%Timeline`) to control whether or not parts of a specification
1362
 
are processed or not.
1363
 
 
1364
 
A *range* of versions means all versions starting with the lower bound up to
1365
 
but excluding the upper bound.  If the lower bound is omitted then it is
1366
 
interpreted as being before the earliest version.  If the upper bound is
1367
 
omitted then it is interpreted as being after the latest version.
1368
 
 
1369
 
For example::
1370
 
 
1371
 
    %Feature SUPPORT_FOO
1372
 
    %Platforms {WIN32_PLATFORM POSIX_PLATFORM MACOS_PLATFORM}
1373
 
    %Timeline {V1_0 V1_1 V2_0 V3_0}
1374
 
 
1375
 
    %If (!SUPPORT_FOO)
1376
 
        // Process this if the SUPPORT_FOO feature is disabled.
1377
 
    %End
1378
 
 
1379
 
    %If (POSIX_PLATFORM || MACOS_PLATFORM)
1380
 
        // Process this if either the POSIX_PLATFORM or MACOS_PLATFORM
1381
 
        // platforms are enabled.
1382
 
    %End
1383
 
 
1384
 
    %If (V1_0 - V2_0)
1385
 
        // Process this if either V1_0 or V1_1 is enabled.
1386
 
    %End
1387
 
 
1388
 
    %If (V2_0 - )
1389
 
        // Process this if either V2_0 or V3_0 is enabled.
1390
 
    %End
1391
 
 
1392
 
    %If (SIP_4_13 - )
1393
 
        // SIP v4.13 and later will process this.
1394
 
    %End
1395
 
 
1396
 
    %If ( - )
1397
 
        // Always process this.
1398
 
    %End
1399
 
 
1400
 
Also note that the only way to specify the logical and of qualifiers is to use
1401
 
nested :directive:`%If` directives.
1402
 
 
1403
 
 
1404
 
.. directive:: %Import
1405
 
 
1406
 
.. parsed-literal::
1407
 
 
1408
 
    %Import(name = *filename*)
1409
 
 
1410
 
This directive is used to import the specification of another module.  This is
1411
 
needed if the current module makes use of any types defined in the imported
1412
 
module, e.g. as an argument to a function, or to sub-class.
1413
 
 
1414
 
If ``name`` cannot be opened then SIP prepends ``name`` with the name of the
1415
 
directory containing the current specification file (i.e. the one containing
1416
 
the :directive:`%Import` directive) and tries again.  If this also fails then
1417
 
SIP prepends ``name`` with each of the directories, in turn, specified by the
1418
 
:option:`-I <sip -I>` command line option.
1419
 
 
1420
 
Directory separators must always be ``/``.
1421
 
 
1422
 
For example::
1423
 
 
1424
 
    %Import qt/qtmod.sip
1425
 
 
1426
 
 
1427
 
.. directive:: %Include
1428
 
 
1429
 
.. parsed-literal::
1430
 
 
1431
 
    %Include(name = *filename* [, optional = [True | False]])
1432
 
 
1433
 
This directive is used to include contents of another file as part of the
1434
 
specification of the current module.  It is the equivalent of the C
1435
 
preprocessor's ``#include`` directive and is used to structure a large module
1436
 
specification into manageable pieces.
1437
 
 
1438
 
:directive:`%Include` follows the same search process as the
1439
 
:directive:`%Import` directive when trying to open ``name``.
1440
 
 
1441
 
if ``optional`` is set then SIP will silently continue processing if the file
1442
 
could not be opened.
1443
 
 
1444
 
Directory separators must always be ``/``.
1445
 
 
1446
 
For example::
1447
 
 
1448
 
    %Include qwidget.sip
1449
 
 
1450
 
 
1451
 
.. directive:: %InitialisationCode
1452
 
 
1453
 
.. parsed-literal::
1454
 
 
1455
 
    %InitialisationCode
1456
 
        *code*
1457
 
    %End
1458
 
 
1459
 
This directive is used to specify handwritten code that is embedded in-line
1460
 
in the generated module initialisation code after the SIP module has been
1461
 
imported but before the module itself has been initialised.
1462
 
 
1463
 
It is typically used to call :c:func:`sipRegisterPyType()`.
1464
 
 
1465
 
For example::
1466
 
 
1467
 
    %InitialisationCode
1468
 
        // The code will be executed when the module is first imported, after
1469
 
        // the SIP module has been imported, but before other module-specific
1470
 
        // initialisation has been completed.
1471
 
    %End
1472
 
 
1473
 
 
1474
 
.. directive:: %InstanceCode
1475
 
 
1476
 
.. versionadded:: 4.14
1477
 
 
1478
 
.. parsed-literal::
1479
 
 
1480
 
    %InstanceCode
1481
 
        *code*
1482
 
    %End
1483
 
 
1484
 
There are a number of circumstances where SIP needs to create an instance of a
1485
 
C++ class but may not be able to do so.  For example the C++ class may be
1486
 
abstract or may not have an argumentless public constructor.  This directive is
1487
 
used in the definition of a class or mapped type to specify handwritten code to
1488
 
create an instance of the C++ class.  For example, if the C++ class is
1489
 
abstract, then the handwritten code may return an instance of a concrete
1490
 
sub-class.
1491
 
 
1492
 
The following variable is made available to the handwritten code:
1493
 
 
1494
 
*type* \*sipCpp
1495
 
    This must be set by the handwritten code to the address of an instance of
1496
 
    the C++ class.  It doesn't matter if the instance is on the heap or not as
1497
 
    it will never be explicitly destroyed.
1498
 
 
1499
 
 
1500
 
.. directive:: %License
1501
 
 
1502
 
.. parsed-literal::
1503
 
 
1504
 
    %License(type = *string*
1505
 
            [, licensee = *string*]
1506
 
            [, signature = *string*]
1507
 
            [, timestamp = *string*])
1508
 
 
1509
 
This directive is used to specify the contents of an optional license
1510
 
dictionary.  The license dictionary is called :data:`__license__` and is stored
1511
 
in the module dictionary.
1512
 
 
1513
 
``type`` is the type of the license and its value in the license dictionary is
1514
 
accessed using the ``"Type"`` key.  No restrictions are placed on the value.
1515
 
 
1516
 
``licensee`` is the optional name of the licensee and its value in the license
1517
 
dictionary is accessed using the ``"Licensee"`` key.  No restrictions are
1518
 
placed on the value.
1519
 
 
1520
 
``signature`` is the license's optional signature and its value in the license
1521
 
dictionary is accessed using the ``"Signature"`` key.  No restrictions are
1522
 
placed on the value.
1523
 
 
1524
 
``timestamp`` is the license's optional timestamp and its value in the license
1525
 
dictionary is accessed using the ``"Timestamp"`` key.  No restrictions are
1526
 
placed on the value.
1527
 
 
1528
 
Note that this directive isn't an attempt to impose any licensing restrictions
1529
 
on a module.  It is simply a method for easily embedding licensing information
1530
 
in a module so that it is accessible to Python scripts.
1531
 
 
1532
 
For example::
1533
 
 
1534
 
    %License "GPL"
1535
 
 
1536
 
 
1537
 
.. directive:: %MappedType
1538
 
 
1539
 
.. parsed-literal::
1540
 
 
1541
 
    template<*type-list*>
1542
 
    %MappedType *type*
1543
 
    {
1544
 
        [:directive:`%TypeHeaderCode`]
1545
 
        [:directive:`%ConvertToTypeCode`]
1546
 
        [:directive:`%ConvertFromTypeCode`]
1547
 
    };
1548
 
 
1549
 
    %MappedType *type*
1550
 
    {
1551
 
        [:directive:`%TypeHeaderCode`]
1552
 
        [:directive:`%ConvertToTypeCode`]
1553
 
        [:directive:`%ConvertFromTypeCode`]
1554
 
    };
1555
 
 
1556
 
This directive is used to define an automatic mapping between a C or C++ type
1557
 
and a Python type.  It can be used as part of a template, or to map a specific
1558
 
type.
1559
 
 
1560
 
When used as part of a template *type* cannot itself refer to a template.  Any
1561
 
occurrences of any of the type names (but not any ``*`` or ``&``) in
1562
 
*type-list* will be replaced by the actual type names used when the template is
1563
 
instantiated.  Template mapped types are instantiated automatically as required
1564
 
(unlike template classes which are only instantiated using ``typedef``).
1565
 
 
1566
 
Any explicit mapped type will be used in preference to any template that maps
1567
 
the same type, ie. a template will not be automatically instantiated if there
1568
 
is an explicit mapped type.
1569
 
 
1570
 
The optional :directive:`%TypeHeaderCode` sub-directive is used to specify the
1571
 
library interface to the type being mapped.
1572
 
 
1573
 
The optional :directive:`%ConvertToTypeCode` sub-directive is used to specify
1574
 
the handwritten code that converts a Python object to an instance of the mapped
1575
 
type.
1576
 
 
1577
 
The optional :directive:`%ConvertFromTypeCode` sub-directive is used to specify
1578
 
the handwritten code that converts an instance of the mapped type to a Python
1579
 
object.
1580
 
 
1581
 
For example::
1582
 
 
1583
 
    template<Type *>
1584
 
    %MappedType QList
1585
 
    {
1586
 
    %TypeHeaderCode
1587
 
    // Include the library interface to the type being mapped.
1588
 
    #include <qlist.h>
1589
 
    %End
1590
 
 
1591
 
    %ConvertToTypeCode
1592
 
        // See if we are just being asked to check the type of the Python
1593
 
        // object.
1594
 
        if (sipIsErr == NULL)
1595
 
        {
1596
 
            // Check it is a list.
1597
 
            if (!PyList_Check(sipPy))
1598
 
                return 0;
1599
 
 
1600
 
            // Now check each element of the list is of the type we expect.
1601
 
            // The template is for a pointer type so we don't disallow None.
1602
 
            for (int i = 0; i < PyList_GET_SIZE(sipPy); ++i)
1603
 
                if (!sipCanConvertToType(PyList_GET_ITEM(sipPy, i),
1604
 
                                         sipType_Type, 0))
1605
 
                    return 0;
1606
 
 
1607
 
            return 1;
1608
 
        }
1609
 
 
1610
 
        // Create the instance on the heap.
1611
 
        QList<Type *> *ql = new QList<Type *>;
1612
 
 
1613
 
        for (int i = 0; i < PyList_GET_SIZE(sipPy); ++i)
1614
 
        {
1615
 
            // Use the SIP API to convert the Python object to the
1616
 
            // corresponding C++ instance.  Note that we apply any ownership
1617
 
            // transfer to the list itself, not the individual elements.
1618
 
            Type *t = reinterpret_cast<Type *>(sipConvertToType(
1619
 
                                                PyList_GET_ITEM(sipPy, i),
1620
 
                                                sipType_Type, 0, 0, 0,
1621
 
                                                sipIsErr));
1622
 
 
1623
 
            if (*sipIsErr)
1624
 
            {
1625
 
                // Tidy up.
1626
 
                delete ql;
1627
 
 
1628
 
                // There is nothing on the heap.
1629
 
                return 0;
1630
 
            }
1631
 
 
1632
 
            // Add the pointer to the C++ instance.
1633
 
            ql->append(t);
1634
 
        }
1635
 
 
1636
 
        // Return the instance on the heap.
1637
 
        *sipCppPtr = ql;
1638
 
 
1639
 
        // Apply the normal transfer.
1640
 
        return sipGetState(sipTransferObj);
1641
 
    %End
1642
 
 
1643
 
    %ConvertFromTypeCode
1644
 
        PyObject *l;
1645
 
 
1646
 
        // Create the Python list of the correct length.
1647
 
        if ((l = PyList_New(sipCpp->size())) == NULL)
1648
 
            return NULL;
1649
 
 
1650
 
        // Go through each element in the C++ instance and convert it to the
1651
 
        // corresponding Python object.
1652
 
        for (int i = 0; i < sipCpp->size(); ++i)
1653
 
        {
1654
 
            Type *t = sipCpp->at(i);
1655
 
            PyObject *tobj;
1656
 
 
1657
 
            if ((tobj = sipConvertFromType(t, sipType_Type, sipTransferObj)) == NULL)
1658
 
            {
1659
 
                // There was an error so garbage collect the Python list.
1660
 
                Py_DECREF(l);
1661
 
                return NULL;
1662
 
            }
1663
 
 
1664
 
            PyList_SET_ITEM(l, i, tobj);
1665
 
        }
1666
 
 
1667
 
        // Return the Python list.
1668
 
        return l;
1669
 
    %End
1670
 
    };
1671
 
 
1672
 
Using this we can use, for example, ``QList<QObject *>`` throughout the
1673
 
module's specification files (and in any module that imports this one).  The
1674
 
generated code will automatically map this to and from a Python list of QObject
1675
 
instances when appropriate.
1676
 
 
1677
 
 
1678
 
.. directive:: %MethodCode
1679
 
 
1680
 
.. parsed-literal::
1681
 
 
1682
 
    %MethodCode
1683
 
        *code*
1684
 
    %End
1685
 
 
1686
 
This directive is used as part of the specification of a global function, class
1687
 
method, operator, constructor or destructor to specify handwritten code that
1688
 
replaces the normally generated call to the function being wrapped.  It is
1689
 
usually used to handle argument types and results that SIP cannot deal with
1690
 
automatically.
1691
 
 
1692
 
Normally the specified code is embedded in-line after the function's arguments
1693
 
have been successfully converted from Python objects to their C or C++
1694
 
equivalents.  In this case the specified code must not include any ``return``
1695
 
statements.
1696
 
 
1697
 
However if the :fanno:`NoArgParser` annotation has been used then the specified
1698
 
code is also responsible for parsing the arguments.  No other code is generated
1699
 
by SIP and the specified code must include a ``return`` statement.
1700
 
 
1701
 
In the context of a destructor the specified code is embedded in-line in the
1702
 
Python type's deallocation function.  Unlike other contexts it supplements
1703
 
rather than replaces the normally generated code, so it must not include code
1704
 
to return the C structure or C++ class instance to the heap.  The code is only
1705
 
called if ownership of the structure or class is with Python.
1706
 
 
1707
 
The specified code must also handle the Python Global Interpreter Lock (GIL).
1708
 
If compatibility with SIP v3.x is required then the GIL must be released
1709
 
immediately before the C++ call and reacquired immediately afterwards as shown
1710
 
in this example fragment::
1711
 
 
1712
 
    Py_BEGIN_ALLOW_THREADS
1713
 
    sipCpp->foo();
1714
 
    Py_END_ALLOW_THREADS
1715
 
 
1716
 
If compatibility with SIP v3.x is not required then this is optional but
1717
 
should be done if the C++ function might block the current thread or take a
1718
 
significant amount of time to execute.  (See :ref:`ref-gil` and the
1719
 
:fanno:`ReleaseGIL` and :fanno:`HoldGIL` annotations.)
1720
 
 
1721
 
If the :fanno:`NoArgParser` annotation has not been used then the following
1722
 
variables are made available to the handwritten code:
1723
 
 
1724
 
*type* a0
1725
 
    There is a variable for each argument of the Python signature (excluding
1726
 
    any ``self`` argument) named ``a0``, ``a1``, etc.  If
1727
 
    ``use_argument_names`` has been set in the :directive:`%Module` directive
1728
 
    then the name of the argument is the real name.  The *type* of the variable
1729
 
    is the same as the type defined in the specification with the following
1730
 
    exceptions:
1731
 
 
1732
 
    - if the argument is only used to return a value (e.g. it is an ``int *``
1733
 
      without an :aanno:`In` annotation) then the type has one less level of
1734
 
      indirection (e.g. it will be an ``int``)
1735
 
    - if the argument is a structure or class (or a reference or a pointer to a
1736
 
      structure or class) then *type* will always be a pointer to the structure
1737
 
      or class.
1738
 
 
1739
 
    Note that handwritten code for destructors never has any arguments.
1740
 
 
1741
 
PyObject \*a0Wrapper
1742
 
    This variable is made available only if the :aanno:`GetWrapper` annotation
1743
 
    is specified for the corresponding argument.  The variable is a pointer to
1744
 
    the Python object that wraps the argument.
1745
 
 
1746
 
    If ``use_argument_names`` has been set in the :directive:`%Module`
1747
 
    directive then the name of the variable is the real name of the argument
1748
 
    with ``Wrapper`` appended.
1749
 
 
1750
 
*type* \*sipCpp
1751
 
    If the directive is used in the context of a class constructor then this
1752
 
    must be set by the handwritten code to the constructed instance.  If it is
1753
 
    set to ``0`` and no Python exception is raised then SIP will continue to
1754
 
    try other Python signatures.
1755
 
    
1756
 
    If the directive is used in the context of a method (but not the standard
1757
 
    binary operator methods, e.g. :meth:`__add__`) or a destructor then this is
1758
 
    a pointer to the C structure or C++ class instance.
1759
 
    
1760
 
    Its *type* is a pointer to the structure or class.
1761
 
    
1762
 
    Standard binary operator methods follow the same convention as global
1763
 
    functions and instead define two arguments called ``a0`` and ``a1``.
1764
 
 
1765
 
sipErrorState sipError
1766
 
    The handwritten code should set this to either ``sipErrorContinue`` or
1767
 
    ``sipErrorFail``, and raise an appropriate Python exception, if an error
1768
 
    is detected.  Its initial value will be ``sipErrorNone``.
1769
 
 
1770
 
    When ``sipErrorContinue`` is used, SIP will remember the exception as the
1771
 
    reason why the particular overloaded callable could not be invoked.  It
1772
 
    will then continue to try the next overloaded callable.  It is typically
1773
 
    used by code that needs to do additional type checking of the callable's
1774
 
    arguments.
1775
 
 
1776
 
    When ``sipErrorFail`` is used, SIP will report the exception immediately
1777
 
    and will not attempt to invoke other overloaded callables.
1778
 
 
1779
 
    ``sipError`` is not provided for destructors.
1780
 
 
1781
 
int sipIsErr
1782
 
    The handwritten code should set this to a non-zero value, and raise an
1783
 
    appropriate Python exception, if an error is detected.  This is the
1784
 
    equivalent of setting ``sipError`` to ``sipErrorFail``.  Its initial value
1785
 
    will be ``0``.
1786
 
 
1787
 
    ``sipIsErr`` is not provided for destructors.
1788
 
 
1789
 
*type* sipRes
1790
 
    The handwritten code should set this to the result to be returned.  The
1791
 
    *type* of the variable is the same as the type defined in the Python
1792
 
    signature in the specification with the following exception:
1793
 
 
1794
 
    - if the argument is a structure or class (or a reference or a pointer to a
1795
 
      structure or class) then *type* will always be a pointer to the structure
1796
 
      or class.
1797
 
 
1798
 
    ``sipRes`` is not provided for inplace operators (e.g. ``+=`` or
1799
 
    :meth:`__imul__`) as their results are handled automatically, nor for class
1800
 
    constructors or destructors.
1801
 
 
1802
 
PyObject \*sipSelf
1803
 
    If the directive is used in the context of a class constructor, destructor
1804
 
    or method then this is the Python object that wraps the structure or class
1805
 
    instance, i.e. ``self``.
1806
 
 
1807
 
bool sipSelfWasArg
1808
 
    This is only made available for non-abstract, virtual methods.  It is set
1809
 
    if ``self`` was explicitly passed as the first argument of the method
1810
 
    rather than being bound to the method.  In other words, the call was::
1811
 
 
1812
 
        Klass.foo(self, ...)
1813
 
 
1814
 
    rather than::
1815
 
 
1816
 
        self.foo(...)
1817
 
 
1818
 
If the :fanno:`NoArgParser` annotation has been used then only the following
1819
 
variables are made available to the handwritten code:
1820
 
 
1821
 
PyObject \*sipArgs
1822
 
    This is the tuple of arguments.
1823
 
 
1824
 
PyObject \*sipKwds
1825
 
    This is the dictionary of keyword arguments.
1826
 
 
1827
 
The following is a complete example::
1828
 
 
1829
 
    class Klass
1830
 
    {
1831
 
    public:
1832
 
        virtual int foo(SIP_PYTUPLE);
1833
 
    %MethodCode
1834
 
            // The C++ API takes a 2 element array of integers but passing a
1835
 
            // two element tuple is more Pythonic.
1836
 
 
1837
 
            int iarr[2];
1838
 
 
1839
 
            if (PyArg_ParseTuple(a0, "ii", &iarr[0], &iarr[1]))
1840
 
            {
1841
 
                Py_BEGIN_ALLOW_THREADS
1842
 
                sipRes = sipSelfWasArg ? sipCpp->Klass::foo(iarr)
1843
 
                                       : sipCpp->foo(iarr);
1844
 
                Py_END_ALLOW_THREADS
1845
 
            }
1846
 
            else
1847
 
            {
1848
 
                // PyArg_ParseTuple() will have raised the exception.
1849
 
                sipIsErr = 1;
1850
 
            }
1851
 
    %End
1852
 
    };
1853
 
 
1854
 
As the example is a virtual method [#]_, note the use of ``sipSelfWasArg`` to
1855
 
determine exactly which implementation of ``foo()`` to call.
1856
 
 
1857
 
If a method is in the ``protected`` section of a C++ class then SIP generates
1858
 
helpers that provide access to method.  However, these are not available if
1859
 
the Python module is being built with ``protected`` redefined as ``public``.
1860
 
 
1861
 
The following pattern should be used to cover all possibilities::
1862
 
 
1863
 
    #if defined(SIP_PROTECTED_IS_PUBLIC)
1864
 
        sipRes = sipSelfWasArg ? sipCpp->Klass::foo(iarr)
1865
 
                               : sipCpp->foo(iarr);
1866
 
    #else
1867
 
        sipRes = sipCpp->sipProtectVirt_foo(sipSelfWasArg, iarr);
1868
 
    #endif
1869
 
 
1870
 
If a method is in the ``protected`` section of a C++ class but is not virtual
1871
 
then the pattern should instead be::
1872
 
 
1873
 
    #if defined(SIP_PROTECTED_IS_PUBLIC)
1874
 
        sipRes = sipCpp->foo(iarr);
1875
 
    #else
1876
 
        sipRes = sipCpp->sipProtect_foo(iarr);
1877
 
    #endif
1878
 
 
1879
 
.. [#] See :directive:`%VirtualCatcherCode` for a description of how SIP
1880
 
       generated code handles the reimplementation of C++ virtual methods in
1881
 
       Python.
1882
 
 
1883
 
 
1884
 
.. directive:: %Module
1885
 
 
1886
 
.. parsed-literal::
1887
 
 
1888
 
    %Module(name = *dotted-name*
1889
 
            [, all_raise_py_exception = [True | False]]
1890
 
            [, call_super_init = [True | False]]
1891
 
            [, default_VirtualErrorHandler = *name*]
1892
 
            [, keyword_arguments = ["None" | "All" | "Optional"]]
1893
 
            [, language = *string*]
1894
 
            [, use_argument_names = [True | False]]
1895
 
            [, version = *integer*])
1896
 
    {
1897
 
        [:directive:`%AutoPyName`]
1898
 
        [:directive:`%Docstring`]
1899
 
    };
1900
 
 
1901
 
This directive is used to specify the name of a module and a number of other
1902
 
attributes.  ``name`` may contain periods to specify that the module is part of
1903
 
a Python package.
1904
 
 
1905
 
``all_raise_py_exception`` specifies that all constructors, functions and
1906
 
methods defined in the module raise a Python exception to indicate that an
1907
 
error occurred.  It is the equivalent of using the :fanno:`RaisesPyException`
1908
 
function annotation on every constructor, function and method.
1909
 
 
1910
 
``call_super_init`` specifies that the ``__init__()`` method of a wrapped class
1911
 
should automatically call it's super-class's ``__init__()`` method passing a
1912
 
dictionary of any unused keyword arguments.  In other words, wrapped classes
1913
 
support cooperative multi-inheritance.  This means that sub-classes, and any
1914
 
mixin classes, should always use call ``super().__init__()`` and not call any
1915
 
super-class's ``__init__()`` method explicitly.
1916
 
 
1917
 
``default_VirtualErrorHandler`` specifies the handler (defined by the
1918
 
:directive:`%VirtualErrorHandler` directive) that is called when a Python
1919
 
re-implementation of any virtual C++ function raises a Python exception.  If no
1920
 
handler is specified for a virtual C++ function then ``PyErr_Print()`` is
1921
 
called.
1922
 
 
1923
 
``keyword_arguments`` specifies the default level of support for Python keyword
1924
 
arguments.  See the :fanno:`KeywordArgs` annotation for an explaination of the
1925
 
possible values and their effect.  If it is not specified then the value
1926
 
implied by the (deprecated) :option:`-k <sip -k>` command line option is used.
1927
 
 
1928
 
``language`` specifies the implementation language of the library being
1929
 
wrapped.  Its value is either ``"C++"`` (the default) or ``"C"``.
1930
 
 
1931
 
When providing handwritten code as part of either the :directive:`%MethodCode`
1932
 
or :directive:`%VirtualCatcherCode` directives the names of the arguments of
1933
 
the function or method are based on the number of the argument, i.e. the first
1934
 
argument is named ``a0``, the second ``a1`` and so on.  ``use_argument_names``
1935
 
is set to specify that the real name of the argument, if any, should be used
1936
 
instead.  It also affects the name of the variable created when the
1937
 
:aanno:`GetWrapper` argument annotation is used.
1938
 
 
1939
 
``version`` is an optional version number that is useful if you (or others)
1940
 
might create other modules that build on this module, i.e. if another module
1941
 
might :directive:`%Import` this module.  Under the covers, a module exports an
1942
 
API that is used by modules that :directive:`%Import` it and the API is given a
1943
 
version number.  A module built on that module knows the version number of the
1944
 
API that it is expecting.  If, when the modules are imported at run-time, the
1945
 
version numbers do not match then a Python exception is raised.  The dependent
1946
 
module must then be re-built using the correct specification files for the base
1947
 
module.
1948
 
 
1949
 
The optional :directive:`%AutoPyName` sub-directive is used to specify a rule
1950
 
for automatically providing Python names.
1951
 
 
1952
 
The optional :directive:`%Docstring` sub-directive is used to specify the
1953
 
module's docstring.
1954
 
 
1955
 
For example::
1956
 
 
1957
 
    %Module(name=PyQt4.QtCore, version=5)
1958
 
 
1959
 
 
1960
 
.. directive:: %ModuleCode
1961
 
 
1962
 
.. parsed-literal::
1963
 
 
1964
 
    %ModuleCode
1965
 
        *code*
1966
 
    %End
1967
 
 
1968
 
This directive is used to specify handwritten code, typically the
1969
 
implementations of utility functions, that can be called by other handwritten
1970
 
code in the module.
1971
 
 
1972
 
For example::
1973
 
 
1974
 
    %ModuleCode
1975
 
    // Print an object on stderr for debugging purposes.
1976
 
    void dump_object(PyObject *o)
1977
 
    {
1978
 
        PyObject_Print(o, stderr, 0);
1979
 
        fprintf(stderr, "\n");
1980
 
    }
1981
 
    %End
1982
 
 
1983
 
.. seealso:: :directive:`%ExportedHeaderCode`, :directive:`%ModuleHeaderCode`
1984
 
 
1985
 
 
1986
 
.. directive:: %ModuleHeaderCode
1987
 
 
1988
 
.. parsed-literal::
1989
 
 
1990
 
    %ModuleHeaderCode
1991
 
        *code*
1992
 
    %End
1993
 
 
1994
 
This directive is used to specify handwritten code, typically the declarations
1995
 
of utility functions, that is placed in a header file that is included by all
1996
 
generated code for the same module.
1997
 
 
1998
 
For example::
1999
 
 
2000
 
    %ModuleHeaderCode
2001
 
    void dump_object(PyObject *o);
2002
 
    %End
2003
 
 
2004
 
.. seealso:: :directive:`%ExportedHeaderCode`, :directive:`%ModuleCode`
2005
 
 
2006
 
 
2007
 
.. directive:: %OptionalInclude
2008
 
 
2009
 
.. parsed-literal::
2010
 
 
2011
 
    %OptionalInclude *filename*
2012
 
 
2013
 
.. deprecated:: 4.12
2014
 
    Use the :directive:`%Include` directive with the ``optional`` argument set
2015
 
    to ``True`` instead.
2016
 
 
2017
 
This directive is identical to the :directive:`%Include` directive except that
2018
 
SIP silently continues processing if *filename* could not be opened.
2019
 
 
2020
 
For example::
2021
 
 
2022
 
    %OptionalInclude license.sip
2023
 
 
2024
 
 
2025
 
.. directive:: %PickleCode
2026
 
 
2027
 
.. parsed-literal::
2028
 
 
2029
 
    %PickleCode
2030
 
        *code*
2031
 
    %End
2032
 
 
2033
 
This directive is used to specify handwritten code to pickle a C structure or
2034
 
C++ class instance.
2035
 
 
2036
 
The following variables are made available to the handwritten code:
2037
 
 
2038
 
*type* \*sipCpp
2039
 
    This is a pointer to the structure or class instance.  Its *type* is a
2040
 
    pointer to the structure or class.
2041
 
 
2042
 
PyObject \*sipRes
2043
 
    The handwritten code must set this to a tuple of the arguments that will
2044
 
    be passed to the type's ``__init__()`` method when the structure or class
2045
 
    instance is unpickled.  If there is an error then the code must raise an
2046
 
    exception and set this to ``NULL``.
2047
 
 
2048
 
For example::
2049
 
 
2050
 
    class Point
2051
 
    {
2052
 
        Point(int x, y);
2053
 
 
2054
 
        int x() const;
2055
 
        int y() const;
2056
 
 
2057
 
    %PickleCode
2058
 
        sipRes = Py_BuildValue("ii", sipCpp->x(), sipCpp->y());
2059
 
    %End
2060
 
    }
2061
 
 
2062
 
Note that SIP works around the Python limitation that prevents nested types
2063
 
being pickled.
2064
 
 
2065
 
Both named and unnamed enums can be pickled automatically without providing any
2066
 
handwritten code.
2067
 
 
2068
 
 
2069
 
.. directive:: %Platforms
2070
 
 
2071
 
.. parsed-literal::
2072
 
 
2073
 
    %Platforms {*name* *name* ...}
2074
 
 
2075
 
This directive is used to declare a set of platforms.  Platforms (along with
2076
 
:directive:`%Feature` and :directive:`%Timeline`) are used by the
2077
 
:directive:`%If` directive to control whether or not parts of a specification
2078
 
are processed or ignored.
2079
 
 
2080
 
Platforms are mutually exclusive - only one platform can be enabled at a time.
2081
 
By default all platforms are disabled.  The SIP :option:`-t <sip -t>` command
2082
 
line option is used to enable a platform.
2083
 
 
2084
 
.. versionadded:: 4.14
2085
 
 
2086
 
If a platform is enabled then SIP will automatically generate a corresponding C
2087
 
preprocessor symbol for use by handwritten code.  The symbol is the name of
2088
 
the platform prefixed by ``SIP_PLATFORM_``.
2089
 
 
2090
 
For example::
2091
 
 
2092
 
    %Platforms {WIN32_PLATFORM POSIX_PLATFORM MACOS_PLATFORM}
2093
 
 
2094
 
    %If (WIN32_PLATFORM)
2095
 
    void undocumented();
2096
 
    %End
2097
 
 
2098
 
    %If (POSIX_PLATFORM)
2099
 
    void documented();
2100
 
    %End
2101
 
 
2102
 
 
2103
 
.. directive:: %PostInitialisationCode
2104
 
 
2105
 
.. parsed-literal::
2106
 
 
2107
 
    %PostInitialisationCode
2108
 
        *code*
2109
 
    %End
2110
 
 
2111
 
This directive is used to specify handwritten code that is embedded in-line
2112
 
at the very end of the generated module initialisation code.
2113
 
 
2114
 
The following variables are made available to the handwritten code:
2115
 
 
2116
 
PyObject \*sipModule
2117
 
    This is the module object returned by ``Py_InitModule()``.
2118
 
 
2119
 
PyObject \*sipModuleDict
2120
 
    This is the module's dictionary object returned by ``Py_ModuleGetDict()``.
2121
 
 
2122
 
For example::
2123
 
 
2124
 
    %PostInitialisationCode
2125
 
        // The code will be executed when the module is first imported and
2126
 
        // after all other initialisation has been completed.
2127
 
    %End
2128
 
 
2129
 
 
2130
 
.. directive:: %PreInitialisationCode
2131
 
 
2132
 
.. parsed-literal::
2133
 
 
2134
 
    %PreInitialisationCode
2135
 
        *code*
2136
 
    %End
2137
 
 
2138
 
This directive is used to specify handwritten code that is embedded in-line
2139
 
at the very start of the generated module initialisation code.
2140
 
 
2141
 
For example::
2142
 
 
2143
 
    %PreInitialisationCode
2144
 
        // The code will be executed when the module is first imported and
2145
 
        // before other initialisation has been completed.
2146
 
    %End
2147
 
 
2148
 
 
2149
 
.. directive:: %Property
2150
 
 
2151
 
.. versionadded:: 4.12
2152
 
 
2153
 
.. parsed-literal::
2154
 
 
2155
 
    %Property(name = *name*, get = *name* [, set = *name*])
2156
 
    {
2157
 
        [:directive:`%Docstring`]
2158
 
    };
2159
 
 
2160
 
This directive is used to define a Python property.  ``name`` is the name of
2161
 
the property.
2162
 
 
2163
 
``get`` is the Python name of the getter method and must refer to a method in
2164
 
the same class.
2165
 
 
2166
 
``set`` is the Python name of the optional setter method and must refer to a
2167
 
method in the same class.
2168
 
 
2169
 
The optional :directive:`%Docstring` sub-directive is used to specify the
2170
 
property's docstring.
2171
 
 
2172
 
For example::
2173
 
 
2174
 
    class Klass
2175
 
    {
2176
 
    public:
2177
 
        int get_count() const;
2178
 
        void set_count();
2179
 
 
2180
 
        %Property(name=count, get=get_count, set=set_count)
2181
 
    };
2182
 
 
2183
 
 
2184
 
.. directive:: %RaiseCode
2185
 
 
2186
 
.. parsed-literal::
2187
 
 
2188
 
    %RaiseCode
2189
 
        *code*
2190
 
    %End
2191
 
 
2192
 
This directive is used as part of the definition of an exception using the
2193
 
:directive:`%Exception` directive to specify handwritten code that raises a
2194
 
Python exception when a C++ exception has been caught.  The code is embedded
2195
 
in-line as the body of a C++ ``catch ()`` clause.
2196
 
 
2197
 
The specified code must handle the Python Global Interpreter Lock (GIL) if
2198
 
necessary.  The GIL must be acquired before any calls to the Python API and
2199
 
released after the last call as shown in this example fragment::
2200
 
 
2201
 
    SIP_BLOCK_THREADS
2202
 
    PyErr_SetNone(PyErr_Exception);
2203
 
    SIP_UNBLOCK_THREADS
2204
 
 
2205
 
Finally, the specified code must not include any ``return`` statements.
2206
 
 
2207
 
The following variable is made available to the handwritten code:
2208
 
 
2209
 
*type* &sipExceptionRef
2210
 
    This is a reference to the caught C++ exception.  The *type* of the
2211
 
    reference is the same as the type defined in the ``throw ()`` specifier.
2212
 
 
2213
 
See the :directive:`%Exception` directive for an example.
2214
 
 
2215
 
 
2216
 
.. directive:: %SetCode
2217
 
 
2218
 
.. parsed-literal::
2219
 
 
2220
 
    %SetCode
2221
 
        *code*
2222
 
    %End
2223
 
 
2224
 
This sub-directive is used in the declaration of a C++ class variable or C
2225
 
structure member to specify handwritten code to convert it from a Python
2226
 
object.  It is usually used to handle types that SIP cannot deal with
2227
 
automatically.
2228
 
 
2229
 
The following variables are made available to the handwritten code:
2230
 
 
2231
 
*type* \*sipCpp
2232
 
    This is a pointer to the structure or class instance.  Its *type* is a
2233
 
    pointer to the structure or class.  It is not made available if the
2234
 
    variable being wrapped is a static class variable.
2235
 
 
2236
 
int sipErr
2237
 
    If the conversion failed then the handwritten code should raise a Python
2238
 
    exception and set this to a non-zero value.  Its initial value will be
2239
 
    automatically set to zero.
2240
 
 
2241
 
PyObject \*sipPy
2242
 
    This is the Python object that the handwritten code should convert.
2243
 
 
2244
 
PyObject \*sipPyType
2245
 
    If the variable being wrapped is a static class variable then this is the
2246
 
    Python type object of the class from which the variable was referenced
2247
 
    (*not* the class in which it is defined).  It may be safely cast to a
2248
 
    PyTypeObject \* or a sipWrapperType \*.
2249
 
 
2250
 
.. seealso:: :directive:`%AccessCode`, :directive:`%GetCode`
2251
 
 
2252
 
 
2253
 
.. directive:: %Timeline
2254
 
 
2255
 
.. parsed-literal::
2256
 
 
2257
 
    %Timeline {*name* *name* ...}
2258
 
 
2259
 
This directive is used to declare a set of versions released over a period of
2260
 
time.  Versions (along with :directive:`%Feature` and :directive:`%Platforms`)
2261
 
are used by the :directive:`%If` directive to control whether or not parts of a
2262
 
specification are processed or ignored.
2263
 
 
2264
 
Versions are mutually exclusive - only one version can be enabled at a time.
2265
 
By default all versions are disabled.  The SIP :option:`-t <sip -t>` command
2266
 
line option is used to enable a version.
2267
 
 
2268
 
The :directive:`%Timeline` directive can be used any number of times in a
2269
 
module to allow multiple libraries to be wrapped in the same module.
2270
 
 
2271
 
.. versionadded:: 4.12
2272
 
 
2273
 
SIP automatically defines a timeline containing all versions of SIP since
2274
 
v4.12.  The name of the version is ``SIP_`` followed by the individual parts of
2275
 
the version number separated by an underscore.  SIP v4.12 is therefore
2276
 
``SIP_4_12`` and SIP v4.13.2 is ``SIP_4_13_2``.
2277
 
 
2278
 
.. versionadded:: 4.14
2279
 
 
2280
 
If a particular version is enabled then SIP will automatically generate a
2281
 
corresponding C preprocessor symbol for use by handwritten code.  The symbol is
2282
 
the name of the version prefixed by ``SIP_TIMELINE_``.
2283
 
 
2284
 
For example::
2285
 
 
2286
 
    %Timeline {V1_0 V1_1 V2_0 V3_0}
2287
 
 
2288
 
    %If (V1_0 - V2_0)
2289
 
    void foo();
2290
 
    %End
2291
 
 
2292
 
    %If (V2_0 -)
2293
 
    void foo(int = 0);
2294
 
    %End
2295
 
 
2296
 
    %If (- SIP_4_13)
2297
 
    void bar();
2298
 
    %End
2299
 
 
2300
 
 
2301
 
.. directive:: %TypeCode
2302
 
 
2303
 
.. parsed-literal::
2304
 
 
2305
 
    %TypeCode
2306
 
        *code*
2307
 
    %End
2308
 
 
2309
 
This directive is used as part of the specification of a C structure, a C++
2310
 
class or a :directive:`%MappedType` directive to specify handwritten code,
2311
 
typically the implementations of utility functions, that can be called by other
2312
 
handwritten code in the structure or class.
2313
 
 
2314
 
For example::
2315
 
 
2316
 
    class Klass
2317
 
    {
2318
 
    %TypeCode
2319
 
    // Print an instance on stderr for debugging purposes.
2320
 
    static void dump_klass(const Klass *k)
2321
 
    {
2322
 
        fprintf(stderr,"Klass %s at %p\n", k->name(), k);
2323
 
    }
2324
 
    %End
2325
 
 
2326
 
        // The rest of the class specification.
2327
 
 
2328
 
    };
2329
 
 
2330
 
Because the scope of the code is normally within the generated file that
2331
 
implements the type, any utility functions would normally be declared
2332
 
``static``.  However a naming convention should still be adopted to prevent
2333
 
clashes of function names within a module in case the SIP ``-j`` command line
2334
 
option is used.
2335
 
 
2336
 
 
2337
 
.. directive:: %TypeHeaderCode
2338
 
 
2339
 
.. parsed-literal::
2340
 
 
2341
 
    %TypeHeaderCode
2342
 
        *code*
2343
 
    %End
2344
 
 
2345
 
This directive is used to specify handwritten code that defines the interface
2346
 
to a C or C++ type being wrapped, either a structure, a class, or a template.
2347
 
It is used within a class definition or a :directive:`%MappedType` directive.
2348
 
 
2349
 
Normally *code* will be a pre-processor ``#include`` statement.
2350
 
 
2351
 
For example::
2352
 
 
2353
 
    // Wrap the Klass class.
2354
 
    class Klass
2355
 
    {
2356
 
    %TypeHeaderCode
2357
 
    #include <klass.h>
2358
 
    %End
2359
 
 
2360
 
        // The rest of the class specification.
2361
 
    };
2362
 
 
2363
 
 
2364
 
.. directive:: %UnitCode
2365
 
 
2366
 
.. parsed-literal::
2367
 
 
2368
 
    %UnitCode
2369
 
        *code*
2370
 
    %End
2371
 
 
2372
 
This directive is used to specify handwritten code that is included at the very
2373
 
start of a generated compilation unit (ie. C or C++ source file).  It is
2374
 
typically used to ``#include`` a C++ precompiled header file.
2375
 
 
2376
 
 
2377
 
.. directive:: %UnitPostIncludeCode
2378
 
 
2379
 
.. versionadded:: 4.11
2380
 
 
2381
 
.. parsed-literal::
2382
 
 
2383
 
    %UnitPostIncludeCode
2384
 
        *code*
2385
 
    %End
2386
 
 
2387
 
This directive is used to specify handwritten code that is included following
2388
 
the ``#include`` of all header files in a generated compilation unit (ie. C or
2389
 
C++ source file).
2390
 
 
2391
 
 
2392
 
.. directive:: %VirtualCatcherCode
2393
 
 
2394
 
.. parsed-literal::
2395
 
 
2396
 
    %VirtualCatcherCode
2397
 
        *code*
2398
 
    %End
2399
 
 
2400
 
For most classes there are corresponding :ref:`generated derived classes
2401
 
<ref-derived-classes>` that contain reimplementations of the class's virtual
2402
 
methods.  These methods (which SIP calls catchers) determine if there is a
2403
 
corresponding Python reimplementation and call it if so.  If there is no Python
2404
 
reimplementation then the method in the original class is called instead.
2405
 
 
2406
 
This directive is used to specify handwritten code that replaces the normally
2407
 
generated call to the Python reimplementation and the handling of any returned
2408
 
results.  It is usually used to handle argument types and results that SIP
2409
 
cannot deal with automatically.
2410
 
 
2411
 
This directive can also be used in the context of a class destructor to
2412
 
specify handwritten code that is embedded in-line in the internal derived
2413
 
class's destructor.
2414
 
 
2415
 
In the context of a method the Python Global Interpreter Lock (GIL) is
2416
 
automatically acquired before the specified code is executed and automatically
2417
 
released afterwards.
2418
 
 
2419
 
In the context of a destructor the specified code must handle the GIL.  The
2420
 
GIL must be acquired before any calls to the Python API and released after the
2421
 
last call as shown in this example fragment::
2422
 
 
2423
 
    SIP_BLOCK_THREADS
2424
 
    Py_DECREF(obj);
2425
 
    SIP_UNBLOCK_THREADS
2426
 
 
2427
 
The following variables are made available to the handwritten code in the
2428
 
context of a method:
2429
 
 
2430
 
*type* a0
2431
 
    There is a variable for each argument of the C++ signature named ``a0``,
2432
 
    ``a1``, etc.  If ``use_argument_names`` has been set in the
2433
 
    :directive:`%Module` directive then the name of the argument is the real
2434
 
    name.  The *type* of the variable is the same as the type defined in the
2435
 
    specification.
2436
 
 
2437
 
int a0Key
2438
 
    There is a variable for each argument of the C++ signature that has a type
2439
 
    where it is important to ensure that the corresponding Python object is not
2440
 
    garbage collected too soon.  This only applies to output arguments that
2441
 
    return ``'\0'`` terminated strings.  The variable would normally be passed
2442
 
    to :c:func:`sipParseResult()` using either the ``A`` or ``B`` format
2443
 
    characters.
2444
 
 
2445
 
    If ``use_argument_names`` has been set in the :directive:`%Module`
2446
 
    directive then the name of the variable is the real name of the argument
2447
 
    with ``Key`` appended.
2448
 
 
2449
 
int sipIsErr
2450
 
    The handwritten code should set this to a non-zero value, and raise an
2451
 
    appropriate Python exception, if an error is detected.
2452
 
 
2453
 
PyObject \*sipMethod
2454
 
    This object is the Python reimplementation of the virtual C++ method.  It
2455
 
    is normally passed to :c:func:`sipCallMethod()`.
2456
 
 
2457
 
*type* sipRes
2458
 
    The handwritten code should set this to the result to be returned.  The
2459
 
    *type* of the variable is the same as the type defined in the C++ signature
2460
 
    in the specification.
2461
 
 
2462
 
int sipResKey
2463
 
    This variable is only made available if the result has a type where it is
2464
 
    important to ensure that the corresponding Python object is not garbage
2465
 
    collected too soon.  This only applies to ``'\0'`` terminated strings.  The
2466
 
    variable would normally be passed to :c:func:`sipParseResult()` using
2467
 
    either the ``A`` or ``B`` format characters.
2468
 
 
2469
 
sipSimpleWrapper \*sipPySelf
2470
 
    This variable is only made available if either the ``a0Key`` or
2471
 
    ``sipResKey`` are made available.  It defines the context within which keys
2472
 
    are unique.  The variable would normally be passed to
2473
 
    :c:func:`sipParseResult()` using the ``S`` format character.
2474
 
 
2475
 
No variables are made available in the context of a destructor.
2476
 
 
2477
 
For example::
2478
 
 
2479
 
    class Klass
2480
 
    {
2481
 
    public:
2482
 
        virtual int foo(SIP_PYTUPLE) [int (int *)];
2483
 
    %MethodCode
2484
 
            // The C++ API takes a 2 element array of integers but passing a
2485
 
            // two element tuple is more Pythonic.
2486
 
 
2487
 
            int iarr[2];
2488
 
 
2489
 
            if (PyArg_ParseTuple(a0, "ii", &iarr[0], &iarr[1]))
2490
 
            {
2491
 
                Py_BEGIN_ALLOW_THREADS
2492
 
                sipRes = sipCpp->Klass::foo(iarr);
2493
 
                Py_END_ALLOW_THREADS
2494
 
            }
2495
 
            else
2496
 
            {
2497
 
                // PyArg_ParseTuple() will have raised the exception.
2498
 
                sipIsErr = 1;
2499
 
            }
2500
 
    %End
2501
 
    %VirtualCatcherCode
2502
 
            // Convert the 2 element array of integers to the two element
2503
 
            // tuple.
2504
 
 
2505
 
            PyObject *result;
2506
 
 
2507
 
            result = sipCallMethod(&sipIsErr, sipMethod, "ii", a0[0], a0[1]);
2508
 
 
2509
 
            if (result != NULL)
2510
 
            {
2511
 
                // Convert the result to the C++ type.
2512
 
                sipParseResult(&sipIsErr, sipMethod, result, "i", &sipRes);
2513
 
 
2514
 
                Py_DECREF(result);
2515
 
            }
2516
 
    %End
2517
 
    };
2518
 
 
2519
 
 
2520
 
.. directive:: %VirtualErrorHandler
2521
 
 
2522
 
.. versionadded:: 4.14
2523
 
 
2524
 
.. parsed-literal::
2525
 
 
2526
 
    %VirtualErrorHandler(name = *name*)
2527
 
        *code*
2528
 
    %End
2529
 
 
2530
 
This directive is used to define the handwritten code that implements a handler
2531
 
that is called when a Python re-implementation of a virtual C++ function raises
2532
 
a Python exception.  If a virtual C++ function does not have a handler the
2533
 
``PyErr_Print()`` function is called.
2534
 
 
2535
 
The handler is called after all tidying up has been completed, with the Python
2536
 
Global Interpreter Lock (GIL) held and from the thread that raised the
2537
 
exception.  If the handler wants to change the execution path by, for example,
2538
 
throwing a C++ exception, it must first release the GIL by calling
2539
 
:c:func:`SIP_RELEASE_GIL`.  It must not call :c:func:`SIP_RELEASE_GIL` if the
2540
 
execution path is not changed.
2541
 
 
2542
 
The following variables are made available to the handwritten code:
2543
 
 
2544
 
sipSimpleWrapper \*sipPySelf
2545
 
    This is the class instance containing the Python reimplementation.
2546
 
 
2547
 
sip_gilstate_t sipGILState
2548
 
    This is an opaque value that must be passed to :c:func:`SIP_RELEASE_GIL` in
2549
 
    order to release the GIL prior to changing the execution path.
2550
 
 
2551
 
For example::
2552
 
 
2553
 
    %VirtualErrorHandler my_handler
2554
 
        PyObject *exception, *value, *traceback;
2555
 
 
2556
 
        PyErr_Fetch(&exception, &value, &traceback);
2557
 
 
2558
 
        SIP_RELEASE_GIL(sipGILState);
2559
 
 
2560
 
        throw my_exception(sipPySelf, exception, value, traceback);
2561
 
    %End
2562
 
 
2563
 
.. seealso:: :fanno:`NoVirtualErrorHandler`, :fanno:`VirtualErrorHandler`, :canno:`VirtualErrorHandler`