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.
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*].
12
Some directives are used to specify handwritten code. Handwritten code must
13
not define names that start with the prefix ``sip``.
16
Revised Directive Syntax
17
------------------------
19
.. versionadded:: 4.12
21
The directive syntax used in older versions has some problems:
23
- it is inconsistent in places
25
- it can be problematic to parse
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
33
The revised syntax is:
37
%Directive(arg = value, ...)
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.
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
52
Sub-directives may be specified in any order. If no sub-directives are
53
specified then the braces can be omitted.
55
If a directive is used to specify handwritten code then it may not have
56
sub-directives. In this case the syntax is:
60
%Directive(arg = value, ...)
64
Ordinary C/C++ statements may also have sub-directives. These will also be
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
75
.. directive:: %AccessCode
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.
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;
100
// This will get converted to None.
105
.. seealso:: :directive:`%GetCode`, :directive:`%SetCode`
110
.. versionadded:: 4.9
114
%API(name = *name*, version = *integer*)
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.
119
See :ref:`ref-incompat-apis` for more detail.
123
%API(name=PyQt4, version=1)
126
.. directive:: %AutoPyName
128
.. versionadded:: 4.12
132
%AutoPyName(remove_leading = *string*)
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.
140
``remove_leading`` is a string that will be removed from the beginning of any
147
%AutoPyName(remove_leading="Q")
151
.. directive:: %BIGetBufferCode
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.
163
The following variables are made available to the handwritten code:
165
Py_buffer \*sipBuffer
166
This is a pointer to the Python buffer structure that the handwritten code
170
This is a pointer to the structure or class instance. Its *type* is a
171
pointer to the structure or class.
174
These are the flags that specify what elements of the ``sipBuffer``
175
structure must be populated.
178
The handwritten code should set this to 0 if there was no error or -1 if
182
This is the Python object that wraps the structure or class instance, i.e.
186
.. directive:: %BIGetCharBufferCode
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.
199
The following variables are made available to the handwritten code:
202
This is a pointer to the structure or class instance. Its *type* is a
203
pointer to the structure or class.
206
This is the pointer used to return the address of the character buffer.
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.
212
:c:macro:`SIP_SSIZE_T` sipSegment
213
This is the number of the segment of the character buffer.
216
This is the Python object that wraps the structure or class instance, i.e.
220
.. directive:: %BIGetReadBufferCode
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.
233
The following variables are made available to the handwritten code:
236
This is a pointer to the structure or class instance. Its *type* is a
237
pointer to the structure or class.
240
This is the pointer used to return the address of the read buffer.
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.
246
:c:macro:`SIP_SSIZE_T` sipSegment
247
This is the number of the segment of the read buffer.
250
This is the Python object that wraps the structure or class instance, i.e.
254
.. directive:: %BIGetSegCountCode
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.
267
The following variables are made available to the handwritten code:
270
This is a pointer to the structure or class instance. Its *type* is a
271
pointer to the structure or class.
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.
277
:c:macro:`SIP_SSIZE_T` sipRes
278
The handwritten code should set this to the number of segments that make
282
This is the Python object that wraps the structure or class instance, i.e.
286
.. directive:: %BIGetWriteBufferCode
290
%BIGetWriteBufferCode
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.
299
The following variables are made available to the handwritten code:
302
This is a pointer to the structure or class instance. Its *type* is a
303
pointer to the structure or class.
306
This is the pointer used to return the address of the write buffer.
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.
312
:c:macro:`SIP_SSIZE_T` sipSegment
313
This is the number of the segment of the write buffer.
316
This is the Python object that wraps the structure or class instance, i.e.
320
.. directive:: %BIReleaseBufferCode
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.
332
The following variables are made available to the handwritten code:
334
Py_buffer \*sipBuffer
335
This is a pointer to the Python buffer structure.
338
This is a pointer to the structure or class instance. Its *type* is a
339
pointer to the structure or class.
342
This is the Python object that wraps the structure or class instance, i.e.
346
.. directive:: %CModule
349
Use the :directive:`%Module` directive with the ``language`` argument set
354
%CModule *name* [*version*]
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.
359
See the :directive:`%Module` directive for an explanation of the version
367
.. directive:: %CompositeModule
371
%CompositeModule(name = *dotted-name*)
373
[:directive:`%Docstring`]
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::
384
Clearly the individual modules should not define module-level objects with the
387
This directive is used to specify the name of a composite module. Any
388
subsequent :directive:`%Module` directive is interpreted as defining a
391
The optional :directive:`%Docstring` sub-directive is used to specify the
396
%CompositeModule PyQt4.Qt
397
%Include QtCore/QtCoremod.sip
398
%Include QtGui/QtGuimod.sip
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.
404
.. directive:: %ConsolidatedModule
408
%ConsolidatedModule(name = *dotted-name*)
410
[:directive:`%Docstring`]
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).
416
This directive is used to specify the name of a consolidated module. Any
417
subsequent :directive:`%Module` directive is interpreted as defining a
420
The optional :directive:`%Docstring` sub-directive is used to specify the
425
%ConsolidatedModule PyQt4._qt
426
%Include QtCore/QtCoremod.sip
427
%Include QtGui/QtGuimod.sip
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.
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.
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.
445
.. directive:: %ConvertFromTypeCode
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
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.
464
The following variables are made available to the handwritten code:
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.
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.
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.
484
The following example converts a ``QList<QWidget *>`` instance to a Python
485
list of ``QWidget`` instances::
490
// Create the Python list of the correct length.
491
if ((l = PyList_New(sipCpp->size())) == NULL)
494
// Go through each element in the C++ instance and convert it to a
496
for (int i = 0; i < sipCpp->size(); ++i)
498
QWidget *w = sipCpp->at(i);
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)
505
// There was an error so garbage collect the Python list.
510
// Add the wrapper to the list.
511
PyList_SET_ITEM(l, i, wobj);
514
// Return the Python list.
519
.. directive:: %ConvertToSubClassCode
523
%ConvertToSubClassCode
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.
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.
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.
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
549
The following variables are made available to the handwritten code:
552
This is a pointer to the C++ class instance.
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.
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
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.
576
sipWrapperType \*sipClass
578
Use ``sipType`` instead.
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
587
The handwritten code must not explicitly return.
589
The following example shows the sub-class conversion code for ``QEvent`` based
590
class hierarchy in PyQt::
594
%ConvertToSubClassCode
595
// QEvent sub-classes provide a unique type ID.
596
switch (sipCpp->type())
599
sipType = sipType_QTimerEvent;
602
case QEvent::KeyPress:
603
case QEvent::KeyRelease:
604
sipType = sipType_QKeyEvent;
607
// Skip the remaining event types to keep the example short.
610
// We don't recognise the type.
615
// The rest of the class specification.
620
.. directive:: %ConvertToTypeCode
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.
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.
639
The following variables are made available to the handwritten code:
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
649
This is the Python object to be converted.
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``
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.
663
The handwritten code must explicitly return an ``int`` the meaning of which
664
depends on the value of ``sipIsErr``.
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
670
If ``sipIsErr`` is not ``NULL`` then a combination of the following flags is
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
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`.
681
The following example converts a Python list of ``QPoint`` instances to a
682
``QList<QPoint>`` instance::
685
// See if we are just being asked to check the type of the Python
689
// Checking whether or not None has been passed instead of a list
690
// has already been done.
691
if (!PyList_Check(sipPy))
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))
702
// The type is valid.
706
// Create the instance on the heap.
707
QList<QPoint> *ql = new QList<QPoint>;
709
for (int i = 0; i < PyList_GET_SIZE(sipPy); ++i)
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),
723
// Deal with any errors.
726
sipReleaseType(qp, sipType_QPoint, state);
731
// There is no temporary instance.
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);
744
// Return the instance.
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);
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.
764
.. directive:: %Copying
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.
779
Copyright (c) 2014 Riverbank Computing Limited
783
.. directive:: %DefaultDocstringFormat
785
.. versionadded:: 4.13
789
%DefaultDocstringFormat(name = ["raw" | "deindented"])
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.
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
800
%DefaultDocstringFormat "deindented"
803
.. directive:: %DefaultEncoding
807
%DefaultEncoding(name = ["ASCII" | "Latin-1" | "UTF-8" | "None"])
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.
814
If the directive is not specified then the default encoding of the last
815
imported module is used, if any.
819
%DefaultEncoding "Latin-1"
822
.. directive:: %DefaultMetatype
826
%DefaultMetatype(name = *dotted-name*)
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.
832
If this is not specified then ``sip.wrappertype`` is used.
834
You can also use the :canno:`Metatype` class annotation to specify the
835
meta-type used by a particular C/C++ type.
837
See the section :ref:`ref-types-metatypes` for more details.
841
%DefaultMetatype PyQt4.QtCore.pyqtWrapperType
844
.. directive:: %DefaultSupertype
848
%DefaultSupertype(name = *dotted-name*)
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.
854
If this is not specified then ``sip.wrapper`` is used.
856
You can also use the :canno:`Supertype` class annotation to specify the
857
super-type used by a particular C/C++ type.
859
See the section :ref:`ref-types-metatypes` for more details.
863
%DefaultSupertype sip.simplewrapper
869
Use the :directive:`%Extract` directive instead.
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.
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.
892
This fragment of documentation is HTML and is local to the module in
898
.. directive:: %Docstring
900
.. versionadded:: 4.10
904
%Docstring(format = ["raw" | "deindented"])
908
This directive is used to specify explicit docstrings for modules, classes,
909
functions, methods and properties.
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.
914
The docstring of a function or method is made up of the concatenated docstrings
915
specified for each of the overloads.
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
923
.. versionadded:: 4.13
925
The format may either be ``"raw"`` or ``"deindented"``. If it is not specified
926
then the value specified by any :directive:`%DefaultDocstringFormat` directive
929
If the format is ``"raw"`` then the docstring is used as it appears in the
932
If the format is ``"deindented"`` then any leading spaces common to all
933
non-blank lines of the docstring are removed.
940
This will be at the start of the class's docstring.
945
%Docstring deindented
946
This will be appended to the class's docstring and will not be indented.
948
This will be indented by four spaces.
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.
959
.. directive:: %Exception
963
%Exception *name* [(*base-exception*)]
965
[:directive:`%TypeHeaderCode`]
966
:directive:`%RaiseCode`
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.
975
*name* is the name of the exception.
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.
981
The optional :directive:`%TypeHeaderCode` sub-directive is used to specify any
982
external interface to the exception being defined.
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.
989
%Exception std::exception(SIP_Exception) /PyName=StdException/
995
const char *detail = sipExceptionRef.what();
998
PyErr_SetString(sipException_std_exception, detail);
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``.
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.
1011
.. directive:: %ExportedDoc
1013
.. deprecated:: 4.12
1014
Use the :directive:`%Extract` directive instead.
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.
1027
Documentation that is specified using this directive will also be included by
1028
modules that :directive:`%Import` it.
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.
1042
.. directive:: %ExportedHeaderCode
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.
1055
.. seealso:: :directive:`%ModuleCode`, :directive:`%ModuleHeaderCode`
1058
.. directive:: %Extract
1060
.. versionadded:: 4.12
1064
%Extract(id = *name* [, order = *integer*])
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.
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
1078
An extract is written to a file using the :option:`-X <sip -X>` command line
1084
This will be the last line because there is no explicit order.
1087
%Extract(id=example, order=20)
1088
This will be the second line.
1091
%Extract(id=example, order=10)
1092
This will be the first line.
1096
.. directive:: %Feature
1100
%Feature(name = *name*)
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.
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.
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_``.
1117
%Feature FOO_SUPPORT
1124
.. directive:: %FinalisationCode
1126
.. versionadded:: 4.15
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.
1140
The following variables are made available to the handwritten code:
1143
This is the Python object that wraps the structure or class instance, i.e.
1147
This is a pointer to the structure or class instance. Its *type* is a
1148
pointer to the structure or class.
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
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.
1168
.. directive:: %GCClearCode
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.
1182
See the section `Supporting Cyclic Garbage Collection
1183
<http://docs.python.org/3/c-api/gcsupport.html>`__ in the Python documentation
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.)
1190
The following variables are made available to the handwritten code:
1193
This is a pointer to the structure or class instance. Its *type* is a
1194
pointer to the structure or class.
1197
The handwritten code should set this to the result to be returned.
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::
1207
obj = reinterpret_cast<PyObject *>(sipCpp->data());
1209
// Clear the pointer.
1212
// Clear the reference.
1220
.. directive:: %GCTraverseCode
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.)
1232
The following variables are made available to the handwritten code:
1235
This is a pointer to the structure or class instance. Its *type* is a
1236
pointer to the structure or class.
1239
This is the visit function provided by the garbage collector.
1242
This is the argument to the visit function provided by the garbage
1246
The handwritten code should set this to the result to be returned.
1248
The following simplified example is taken from PyQt's ``QCustomEvent`` class::
1254
obj = reinterpret_cast<PyObject *>(sipCpp->data());
1256
// Call the visit function if there was an object.
1258
sipRes = sipVisit(obj, sipArg);
1264
.. directive:: %GetCode
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.
1276
The following variables are made available to the handwritten code:
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.
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``.
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 \*.
1299
* In this contrived example the C library we are wrapping actually
1300
* defines this as char buffer[100] which SIP cannot handle
1306
sipPy = PyString_FromStringAndSize(sipCpp->buffer, 100);
1313
if (PyString_AsStringAndSize(sipPy, &ptr, &length) == -1)
1317
else if (length != 100)
1320
* Raise an exception because the length isn't exactly
1324
PyErr_SetString(PyExc_ValueError,
1325
"an Entity.buffer must be exactly 100 bytes");
1330
memcpy(sipCpp->buffer, ptr, 100);
1336
.. seealso:: :directive:`%AccessCode`, :directive:`%SetCode`
1351
*expression* ::= [*ored-qualifiers* | *range*]
1353
*ored-qualifiers* ::= [*qualifier* | *qualifier* **||** *ored-qualifiers*]
1355
*qualifier* ::= [**!**] [*feature* | *platform*]
1357
*range* ::= [*version*] **-** [*version*]
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.
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.
1371
%Feature SUPPORT_FOO
1372
%Platforms {WIN32_PLATFORM POSIX_PLATFORM MACOS_PLATFORM}
1373
%Timeline {V1_0 V1_1 V2_0 V3_0}
1376
// Process this if the SUPPORT_FOO feature is disabled.
1379
%If (POSIX_PLATFORM || MACOS_PLATFORM)
1380
// Process this if either the POSIX_PLATFORM or MACOS_PLATFORM
1381
// platforms are enabled.
1385
// Process this if either V1_0 or V1_1 is enabled.
1389
// Process this if either V2_0 or V3_0 is enabled.
1393
// SIP v4.13 and later will process this.
1397
// Always process this.
1400
Also note that the only way to specify the logical and of qualifiers is to use
1401
nested :directive:`%If` directives.
1404
.. directive:: %Import
1408
%Import(name = *filename*)
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.
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.
1420
Directory separators must always be ``/``.
1424
%Import qt/qtmod.sip
1427
.. directive:: %Include
1431
%Include(name = *filename* [, optional = [True | False]])
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.
1438
:directive:`%Include` follows the same search process as the
1439
:directive:`%Import` directive when trying to open ``name``.
1441
if ``optional`` is set then SIP will silently continue processing if the file
1442
could not be opened.
1444
Directory separators must always be ``/``.
1448
%Include qwidget.sip
1451
.. directive:: %InitialisationCode
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.
1463
It is typically used to call :c:func:`sipRegisterPyType()`.
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.
1474
.. directive:: %InstanceCode
1476
.. versionadded:: 4.14
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
1492
The following variable is made available to the handwritten code:
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.
1500
.. directive:: %License
1504
%License(type = *string*
1505
[, licensee = *string*]
1506
[, signature = *string*]
1507
[, timestamp = *string*])
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.
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.
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.
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.
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.
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.
1537
.. directive:: %MappedType
1541
template<*type-list*>
1544
[:directive:`%TypeHeaderCode`]
1545
[:directive:`%ConvertToTypeCode`]
1546
[:directive:`%ConvertFromTypeCode`]
1551
[:directive:`%TypeHeaderCode`]
1552
[:directive:`%ConvertToTypeCode`]
1553
[:directive:`%ConvertFromTypeCode`]
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
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``).
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.
1570
The optional :directive:`%TypeHeaderCode` sub-directive is used to specify the
1571
library interface to the type being mapped.
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
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
1587
// Include the library interface to the type being mapped.
1592
// See if we are just being asked to check the type of the Python
1594
if (sipIsErr == NULL)
1596
// Check it is a list.
1597
if (!PyList_Check(sipPy))
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),
1610
// Create the instance on the heap.
1611
QList<Type *> *ql = new QList<Type *>;
1613
for (int i = 0; i < PyList_GET_SIZE(sipPy); ++i)
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,
1628
// There is nothing on the heap.
1632
// Add the pointer to the C++ instance.
1636
// Return the instance on the heap.
1639
// Apply the normal transfer.
1640
return sipGetState(sipTransferObj);
1643
%ConvertFromTypeCode
1646
// Create the Python list of the correct length.
1647
if ((l = PyList_New(sipCpp->size())) == NULL)
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)
1654
Type *t = sipCpp->at(i);
1657
if ((tobj = sipConvertFromType(t, sipType_Type, sipTransferObj)) == NULL)
1659
// There was an error so garbage collect the Python list.
1664
PyList_SET_ITEM(l, i, tobj);
1667
// Return the Python list.
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.
1678
.. directive:: %MethodCode
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
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``
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.
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.
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::
1712
Py_BEGIN_ALLOW_THREADS
1714
Py_END_ALLOW_THREADS
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.)
1721
If the :fanno:`NoArgParser` annotation has not been used then the following
1722
variables are made available to the handwritten code:
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
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
1739
Note that handwritten code for destructors never has any arguments.
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.
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.
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.
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.
1760
Its *type* is a pointer to the structure or class.
1762
Standard binary operator methods follow the same convention as global
1763
functions and instead define two arguments called ``a0`` and ``a1``.
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``.
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
1776
When ``sipErrorFail`` is used, SIP will report the exception immediately
1777
and will not attempt to invoke other overloaded callables.
1779
``sipError`` is not provided for destructors.
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
1787
``sipIsErr`` is not provided for destructors.
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:
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
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.
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``.
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::
1812
Klass.foo(self, ...)
1818
If the :fanno:`NoArgParser` annotation has been used then only the following
1819
variables are made available to the handwritten code:
1822
This is the tuple of arguments.
1825
This is the dictionary of keyword arguments.
1827
The following is a complete example::
1832
virtual int foo(SIP_PYTUPLE);
1834
// The C++ API takes a 2 element array of integers but passing a
1835
// two element tuple is more Pythonic.
1839
if (PyArg_ParseTuple(a0, "ii", &iarr[0], &iarr[1]))
1841
Py_BEGIN_ALLOW_THREADS
1842
sipRes = sipSelfWasArg ? sipCpp->Klass::foo(iarr)
1843
: sipCpp->foo(iarr);
1844
Py_END_ALLOW_THREADS
1848
// PyArg_ParseTuple() will have raised the exception.
1854
As the example is a virtual method [#]_, note the use of ``sipSelfWasArg`` to
1855
determine exactly which implementation of ``foo()`` to call.
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``.
1861
The following pattern should be used to cover all possibilities::
1863
#if defined(SIP_PROTECTED_IS_PUBLIC)
1864
sipRes = sipSelfWasArg ? sipCpp->Klass::foo(iarr)
1865
: sipCpp->foo(iarr);
1867
sipRes = sipCpp->sipProtectVirt_foo(sipSelfWasArg, iarr);
1870
If a method is in the ``protected`` section of a C++ class but is not virtual
1871
then the pattern should instead be::
1873
#if defined(SIP_PROTECTED_IS_PUBLIC)
1874
sipRes = sipCpp->foo(iarr);
1876
sipRes = sipCpp->sipProtect_foo(iarr);
1879
.. [#] See :directive:`%VirtualCatcherCode` for a description of how SIP
1880
generated code handles the reimplementation of C++ virtual methods in
1884
.. directive:: %Module
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*])
1897
[:directive:`%AutoPyName`]
1898
[:directive:`%Docstring`]
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
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.
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.
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
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.
1928
``language`` specifies the implementation language of the library being
1929
wrapped. Its value is either ``"C++"`` (the default) or ``"C"``.
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.
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
1949
The optional :directive:`%AutoPyName` sub-directive is used to specify a rule
1950
for automatically providing Python names.
1952
The optional :directive:`%Docstring` sub-directive is used to specify the
1957
%Module(name=PyQt4.QtCore, version=5)
1960
.. directive:: %ModuleCode
1968
This directive is used to specify handwritten code, typically the
1969
implementations of utility functions, that can be called by other handwritten
1975
// Print an object on stderr for debugging purposes.
1976
void dump_object(PyObject *o)
1978
PyObject_Print(o, stderr, 0);
1979
fprintf(stderr, "\n");
1983
.. seealso:: :directive:`%ExportedHeaderCode`, :directive:`%ModuleHeaderCode`
1986
.. directive:: %ModuleHeaderCode
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.
2001
void dump_object(PyObject *o);
2004
.. seealso:: :directive:`%ExportedHeaderCode`, :directive:`%ModuleCode`
2007
.. directive:: %OptionalInclude
2011
%OptionalInclude *filename*
2013
.. deprecated:: 4.12
2014
Use the :directive:`%Include` directive with the ``optional`` argument set
2015
to ``True`` instead.
2017
This directive is identical to the :directive:`%Include` directive except that
2018
SIP silently continues processing if *filename* could not be opened.
2022
%OptionalInclude license.sip
2025
.. directive:: %PickleCode
2033
This directive is used to specify handwritten code to pickle a C structure or
2036
The following variables are made available to the handwritten code:
2039
This is a pointer to the structure or class instance. Its *type* is a
2040
pointer to the structure or class.
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``.
2058
sipRes = Py_BuildValue("ii", sipCpp->x(), sipCpp->y());
2062
Note that SIP works around the Python limitation that prevents nested types
2065
Both named and unnamed enums can be pickled automatically without providing any
2069
.. directive:: %Platforms
2073
%Platforms {*name* *name* ...}
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.
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.
2084
.. versionadded:: 4.14
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_``.
2092
%Platforms {WIN32_PLATFORM POSIX_PLATFORM MACOS_PLATFORM}
2094
%If (WIN32_PLATFORM)
2095
void undocumented();
2098
%If (POSIX_PLATFORM)
2103
.. directive:: %PostInitialisationCode
2107
%PostInitialisationCode
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.
2114
The following variables are made available to the handwritten code:
2116
PyObject \*sipModule
2117
This is the module object returned by ``Py_InitModule()``.
2119
PyObject \*sipModuleDict
2120
This is the module's dictionary object returned by ``Py_ModuleGetDict()``.
2124
%PostInitialisationCode
2125
// The code will be executed when the module is first imported and
2126
// after all other initialisation has been completed.
2130
.. directive:: %PreInitialisationCode
2134
%PreInitialisationCode
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.
2143
%PreInitialisationCode
2144
// The code will be executed when the module is first imported and
2145
// before other initialisation has been completed.
2149
.. directive:: %Property
2151
.. versionadded:: 4.12
2155
%Property(name = *name*, get = *name* [, set = *name*])
2157
[:directive:`%Docstring`]
2160
This directive is used to define a Python property. ``name`` is the name of
2163
``get`` is the Python name of the getter method and must refer to a method in
2166
``set`` is the Python name of the optional setter method and must refer to a
2167
method in the same class.
2169
The optional :directive:`%Docstring` sub-directive is used to specify the
2170
property's docstring.
2177
int get_count() const;
2180
%Property(name=count, get=get_count, set=set_count)
2184
.. directive:: %RaiseCode
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.
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::
2202
PyErr_SetNone(PyErr_Exception);
2205
Finally, the specified code must not include any ``return`` statements.
2207
The following variable is made available to the handwritten code:
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.
2213
See the :directive:`%Exception` directive for an example.
2216
.. directive:: %SetCode
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
2229
The following variables are made available to the handwritten code:
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.
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.
2242
This is the Python object that the handwritten code should convert.
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 \*.
2250
.. seealso:: :directive:`%AccessCode`, :directive:`%GetCode`
2253
.. directive:: %Timeline
2257
%Timeline {*name* *name* ...}
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.
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.
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.
2271
.. versionadded:: 4.12
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``.
2278
.. versionadded:: 4.14
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_``.
2286
%Timeline {V1_0 V1_1 V2_0 V3_0}
2301
.. directive:: %TypeCode
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.
2319
// Print an instance on stderr for debugging purposes.
2320
static void dump_klass(const Klass *k)
2322
fprintf(stderr,"Klass %s at %p\n", k->name(), k);
2326
// The rest of the class specification.
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
2337
.. directive:: %TypeHeaderCode
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.
2349
Normally *code* will be a pre-processor ``#include`` statement.
2353
// Wrap the Klass class.
2360
// The rest of the class specification.
2364
.. directive:: %UnitCode
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.
2377
.. directive:: %UnitPostIncludeCode
2379
.. versionadded:: 4.11
2383
%UnitPostIncludeCode
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
2392
.. directive:: %VirtualCatcherCode
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.
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.
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
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.
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::
2427
The following variables are made available to the handwritten code in the
2428
context of a method:
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
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
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.
2450
The handwritten code should set this to a non-zero value, and raise an
2451
appropriate Python exception, if an error is detected.
2453
PyObject \*sipMethod
2454
This object is the Python reimplementation of the virtual C++ method. It
2455
is normally passed to :c:func:`sipCallMethod()`.
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.
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.
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.
2475
No variables are made available in the context of a destructor.
2482
virtual int foo(SIP_PYTUPLE) [int (int *)];
2484
// The C++ API takes a 2 element array of integers but passing a
2485
// two element tuple is more Pythonic.
2489
if (PyArg_ParseTuple(a0, "ii", &iarr[0], &iarr[1]))
2491
Py_BEGIN_ALLOW_THREADS
2492
sipRes = sipCpp->Klass::foo(iarr);
2493
Py_END_ALLOW_THREADS
2497
// PyArg_ParseTuple() will have raised the exception.
2502
// Convert the 2 element array of integers to the two element
2507
result = sipCallMethod(&sipIsErr, sipMethod, "ii", a0[0], a0[1]);
2511
// Convert the result to the C++ type.
2512
sipParseResult(&sipIsErr, sipMethod, result, "i", &sipRes);
2520
.. directive:: %VirtualErrorHandler
2522
.. versionadded:: 4.14
2526
%VirtualErrorHandler(name = *name*)
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.
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.
2542
The following variables are made available to the handwritten code:
2544
sipSimpleWrapper \*sipPySelf
2545
This is the class instance containing the Python reimplementation.
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.
2553
%VirtualErrorHandler my_handler
2554
PyObject *exception, *value, *traceback;
2556
PyErr_Fetch(&exception, &value, &traceback);
2558
SIP_RELEASE_GIL(sipGILState);
2560
throw my_exception(sipPySelf, exception, value, traceback);
2563
.. seealso:: :fanno:`NoVirtualErrorHandler`, :fanno:`VirtualErrorHandler`, :canno:`VirtualErrorHandler`