-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextending.html
More file actions
1389 lines (1326 loc) · 138 KB
/
extending.html
File metadata and controls
1389 lines (1326 loc) · 138 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_TW">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>1. 以 C 或 C++ 擴充 Python — Python 3.7.0 說明文件</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/translations.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="在 Python 3.7.0 說明文件 中搜尋"
href="../_static/opensearch.xml"/>
<link rel="author" title="關於這些文件" href="../about.html" />
<link rel="index" title="索引" href="../genindex.html" />
<link rel="search" title="搜尋" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="2. Defining Extension Types: Tutorial" href="newtypes_tutorial.html" />
<link rel="prev" title="Extending and Embedding the Python Interpreter" href="index.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/extending/extending.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<h3>瀏覽</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模組索引"
>模組</a> |</li>
<li class="right" >
<a href="newtypes_tutorial.html" title="2. Defining Extension Types: Tutorial"
accesskey="N">下一頁</a> |</li>
<li class="right" >
<a href="index.html" title="Extending and Embedding the Python Interpreter"
accesskey="P">上一頁</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> »</li>
<li>
<span class="language_switcher_placeholder">zh_TW</span>
<span class="version_switcher_placeholder">3.7.0</span>
<a href="../index.html">Documentation </a> »
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Extending and Embedding the Python Interpreter</a> »</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="extending-python-with-c-or-c">
<span id="extending-intro"></span><h1>1. 以 C 或 C++ 擴充 Python<a class="headerlink" href="#extending-python-with-c-or-c" title="本標題的永久連結">¶</a></h1>
<p>It is quite easy to add new built-in modules to Python, if you know how to
program in C. Such <em class="dfn">extension modules</em> can do two things that can’t be
done directly in Python: they can implement new built-in object types, and they
can call C library functions and system calls.</p>
<p>To support extensions, the Python API (Application Programmers Interface)
defines a set of functions, macros and variables that provide access to most
aspects of the Python run-time system. The Python API is incorporated in a C
source file by including the header <code class="docutils literal notranslate"><span class="pre">"Python.h"</span></code>.</p>
<p>The compilation of an extension module depends on its intended use as well as on
your system setup; details are given in later chapters.</p>
<div class="admonition note">
<p class="first admonition-title">備註</p>
<p class="last">The C extension interface is specific to CPython, and extension modules do
not work on other Python implementations. In many cases, it is possible to
avoid writing C extensions and preserve portability to other implementations.
For example, if your use case is calling C library functions or system calls,
you should consider using the <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> module or the <a class="reference external" href="https://cffi.readthedocs.io/">cffi</a> library rather than writing
custom C code.
These modules let you write Python code to interface with C code and are more
portable between implementations of Python than writing and compiling a C
extension module.</p>
</div>
<div class="section" id="a-simple-example">
<span id="extending-simpleexample"></span><h2>1.1. A Simple Example<a class="headerlink" href="#a-simple-example" title="本標題的永久連結">¶</a></h2>
<p>Let’s create an extension module called <code class="docutils literal notranslate"><span class="pre">spam</span></code> (the favorite food of Monty
Python fans…) and let’s say we want to create a Python interface to the C
library function <code class="xref c c-func docutils literal notranslate"><span class="pre">system()</span></code> <a class="footnote-reference" href="#id5" id="id1">[1]</a>. This function takes a null-terminated
character string as argument and returns an integer. We want this function to
be callable from Python as follows:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">spam</span>
<span class="gp">>>> </span><span class="n">status</span> <span class="o">=</span> <span class="n">spam</span><span class="o">.</span><span class="n">system</span><span class="p">(</span><span class="s2">"ls -l"</span><span class="p">)</span>
</pre></div>
</div>
<p>Begin by creating a file <code class="file docutils literal notranslate"><span class="pre">spammodule.c</span></code>. (Historically, if a module is
called <code class="docutils literal notranslate"><span class="pre">spam</span></code>, the C file containing its implementation is called
<code class="file docutils literal notranslate"><span class="pre">spammodule.c</span></code>; if the module name is very long, like <code class="docutils literal notranslate"><span class="pre">spammify</span></code>, the
module name can be just <code class="file docutils literal notranslate"><span class="pre">spammify.c</span></code>.)</p>
<p>The first line of our file can be:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf"><Python.h></span><span class="cp"></span>
</pre></div>
</div>
<p>which pulls in the Python API (you can add a comment describing the purpose of
the module and a copyright notice if you like).</p>
<div class="admonition note">
<p class="first admonition-title">備註</p>
<p class="last">Since Python may define some pre-processor definitions which affect the standard
headers on some systems, you <em>must</em> include <code class="file docutils literal notranslate"><span class="pre">Python.h</span></code> before any standard
headers are included.</p>
</div>
<p>All user-visible symbols defined by <code class="file docutils literal notranslate"><span class="pre">Python.h</span></code> have a prefix of <code class="docutils literal notranslate"><span class="pre">Py</span></code> or
<code class="docutils literal notranslate"><span class="pre">PY</span></code>, except those defined in standard header files. For convenience, and
since they are used extensively by the Python interpreter, <code class="docutils literal notranslate"><span class="pre">"Python.h"</span></code>
includes a few standard header files: <code class="docutils literal notranslate"><span class="pre"><stdio.h></span></code>, <code class="docutils literal notranslate"><span class="pre"><string.h></span></code>,
<code class="docutils literal notranslate"><span class="pre"><errno.h></span></code>, and <code class="docutils literal notranslate"><span class="pre"><stdlib.h></span></code>. If the latter header file does not exist on
your system, it declares the functions <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code>, <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> and
<code class="xref c c-func docutils literal notranslate"><span class="pre">realloc()</span></code> directly.</p>
<p>The next thing we add to our module file is the C function that will be called
when the Python expression <code class="docutils literal notranslate"><span class="pre">spam.system(string)</span></code> is evaluated (we’ll see
shortly how it ends up being called):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">spam_system</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">command</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">sts</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">"s"</span><span class="p">,</span> <span class="o">&</span><span class="n">command</span><span class="p">))</span>
<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="n">sts</span> <span class="o">=</span> <span class="n">system</span><span class="p">(</span><span class="n">command</span><span class="p">);</span>
<span class="k">return</span> <span class="n">PyLong_FromLong</span><span class="p">(</span><span class="n">sts</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>There is a straightforward translation from the argument list in Python (for
example, the single expression <code class="docutils literal notranslate"><span class="pre">"ls</span> <span class="pre">-l"</span></code>) to the arguments passed to the C
function. The C function always has two arguments, conventionally named <em>self</em>
and <em>args</em>.</p>
<p>The <em>self</em> argument points to the module object for module-level functions;
for a method it would point to the object instance.</p>
<p>The <em>args</em> argument will be a pointer to a Python tuple object containing the
arguments. Each item of the tuple corresponds to an argument in the call’s
argument list. The arguments are Python objects — in order to do anything
with them in our C function we have to convert them to C values. The function
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> in the Python API checks the argument types and
converts them to C values. It uses a template string to determine the required
types of the arguments as well as the types of the C variables into which to
store the converted values. More about this later.</p>
<p><a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> returns true (nonzero) if all arguments have the right
type and its components have been stored in the variables whose addresses are
passed. It returns false (zero) if an invalid argument list was passed. In the
latter case it also raises an appropriate exception so the calling function can
return <em>NULL</em> immediately (as we saw in the example).</p>
</div>
<div class="section" id="intermezzo-errors-and-exceptions">
<span id="extending-errors"></span><h2>1.2. Intermezzo: Errors and Exceptions<a class="headerlink" href="#intermezzo-errors-and-exceptions" title="本標題的永久連結">¶</a></h2>
<p>An important convention throughout the Python interpreter is the following: when
a function fails, it should set an exception condition and return an error value
(usually a <em>NULL</em> pointer). Exceptions are stored in a static global variable
inside the interpreter; if this variable is <em>NULL</em> no exception has occurred. A
second global variable stores the 「associated value」 of the exception (the
second argument to <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a>). A third variable contains the stack
traceback in case the error originated in Python code. These three variables
are the C equivalents of the result in Python of <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a> (see the
section on module <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> in the Python Library Reference). It is important
to know about them to understand how errors are passed around.</p>
<p>The Python API defines a number of functions to set various types of exceptions.</p>
<p>The most common one is <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_SetString" title="PyErr_SetString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetString()</span></code></a>. Its arguments are an exception
object and a C string. The exception object is usually a predefined object like
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ZeroDivisionError</span></code>. The C string indicates the cause of the error
and is converted to a Python string object and stored as the 「associated value」
of the exception.</p>
<p>Another useful function is <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_SetFromErrno" title="PyErr_SetFromErrno"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetFromErrno()</span></code></a>, which only takes an
exception argument and constructs the associated value by inspection of the
global variable <code class="xref c c-data docutils literal notranslate"><span class="pre">errno</span></code>. The most general function is
<a class="reference internal" href="../c-api/exceptions.html#c.PyErr_SetObject" title="PyErr_SetObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetObject()</span></code></a>, which takes two object arguments, the exception and
its associated value. You don’t need to <a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> the objects passed
to any of these functions.</p>
<p>You can test non-destructively whether an exception has been set with
<a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a>. This returns the current exception object, or <em>NULL</em>
if no exception has occurred. You normally don’t need to call
<a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a> to see whether an error occurred in a function call,
since you should be able to tell from the return value.</p>
<p>When a function <em>f</em> that calls another function <em>g</em> detects that the latter
fails, <em>f</em> should itself return an error value (usually <em>NULL</em> or <code class="docutils literal notranslate"><span class="pre">-1</span></code>). It
should <em>not</em> call one of the <code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_*()</span></code> functions — one has already
been called by <em>g</em>. <em>f</em>’s caller is then supposed to also return an error
indication to <em>its</em> caller, again <em>without</em> calling <code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_*()</span></code>, and so on
— the most detailed cause of the error was already reported by the function
that first detected it. Once the error reaches the Python interpreter’s main
loop, this aborts the currently executing Python code and tries to find an
exception handler specified by the Python programmer.</p>
<p>(There are situations where a module can actually give a more detailed error
message by calling another <code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_*()</span></code> function, and in such cases it is
fine to do so. As a general rule, however, this is not necessary, and can cause
information about the cause of the error to be lost: most operations can fail
for a variety of reasons.)</p>
<p>To ignore an exception set by a function call that failed, the exception
condition must be cleared explicitly by calling <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Clear" title="PyErr_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Clear()</span></code></a>. The only
time C code should call <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Clear" title="PyErr_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Clear()</span></code></a> is if it doesn’t want to pass the
error on to the interpreter but wants to handle it completely by itself
(possibly by trying something else, or pretending nothing went wrong).</p>
<p>Every failing <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> call must be turned into an exception — the
direct caller of <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> (or <code class="xref c c-func docutils literal notranslate"><span class="pre">realloc()</span></code>) must call
<a class="reference internal" href="../c-api/exceptions.html#c.PyErr_NoMemory" title="PyErr_NoMemory"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_NoMemory()</span></code></a> and return a failure indicator itself. All the
object-creating functions (for example, <a class="reference internal" href="../c-api/long.html#c.PyLong_FromLong" title="PyLong_FromLong"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyLong_FromLong()</span></code></a>) already do
this, so this note is only relevant to those who call <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> directly.</p>
<p>Also note that, with the important exception of <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> and
friends, functions that return an integer status usually return a positive value
or zero for success and <code class="docutils literal notranslate"><span class="pre">-1</span></code> for failure, like Unix system calls.</p>
<p>Finally, be careful to clean up garbage (by making <a class="reference internal" href="../c-api/refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a> or
<a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> calls for objects you have already created) when you return
an error indicator!</p>
<p>The choice of which exception to raise is entirely yours. There are predeclared
C objects corresponding to all built-in Python exceptions, such as
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ZeroDivisionError</span></code>, which you can use directly. Of course, you
should choose exceptions wisely — don’t use <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_TypeError</span></code> to mean
that a file couldn’t be opened (that should probably be <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_IOError</span></code>).
If something’s wrong with the argument list, the <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>
function usually raises <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_TypeError</span></code>. If you have an argument whose
value must be in a particular range or must satisfy other conditions,
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ValueError</span></code> is appropriate.</p>
<p>You can also define a new exception that is unique to your module. For this, you
usually declare a static object variable at the beginning of your file:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">SpamError</span><span class="p">;</span>
</pre></div>
</div>
<p>and initialize it in your module’s initialization function (<code class="xref c c-func docutils literal notranslate"><span class="pre">PyInit_spam()</span></code>)
with an exception object (leaving out the error checking for now):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyMODINIT_FUNC</span>
<span class="nf">PyInit_spam</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">PyObject</span> <span class="o">*</span><span class="n">m</span><span class="p">;</span>
<span class="n">m</span> <span class="o">=</span> <span class="n">PyModule_Create</span><span class="p">(</span><span class="o">&</span><span class="n">spammodule</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="n">m</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="n">SpamError</span> <span class="o">=</span> <span class="n">PyErr_NewException</span><span class="p">(</span><span class="s">"spam.error"</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">);</span>
<span class="n">Py_INCREF</span><span class="p">(</span><span class="n">SpamError</span><span class="p">);</span>
<span class="n">PyModule_AddObject</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="s">"error"</span><span class="p">,</span> <span class="n">SpamError</span><span class="p">);</span>
<span class="k">return</span> <span class="n">m</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Note that the Python name for the exception object is <code class="xref py py-exc docutils literal notranslate"><span class="pre">spam.error</span></code>. The
<a class="reference internal" href="../c-api/exceptions.html#c.PyErr_NewException" title="PyErr_NewException"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_NewException()</span></code></a> function may create a class with the base class
being <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> (unless another class is passed in instead of <em>NULL</em>),
described in <a class="reference internal" href="../library/exceptions.html#bltin-exceptions"><span class="std std-ref">內建的例外</span></a>.</p>
<p>Note also that the <code class="xref c c-data docutils literal notranslate"><span class="pre">SpamError</span></code> variable retains a reference to the newly
created exception class; this is intentional! Since the exception could be
removed from the module by external code, an owned reference to the class is
needed to ensure that it will not be discarded, causing <code class="xref c c-data docutils literal notranslate"><span class="pre">SpamError</span></code> to
become a dangling pointer. Should it become a dangling pointer, C code which
raises the exception could cause a core dump or other unintended side effects.</p>
<p>We discuss the use of <code class="docutils literal notranslate"><span class="pre">PyMODINIT_FUNC</span></code> as a function return type later in this
sample.</p>
<p>The <code class="xref py py-exc docutils literal notranslate"><span class="pre">spam.error</span></code> exception can be raised in your extension module using a
call to <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_SetString" title="PyErr_SetString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetString()</span></code></a> as shown below:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">spam_system</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">command</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">sts</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">"s"</span><span class="p">,</span> <span class="o">&</span><span class="n">command</span><span class="p">))</span>
<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="n">sts</span> <span class="o">=</span> <span class="n">system</span><span class="p">(</span><span class="n">command</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="n">sts</span> <span class="o"><</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
<span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">SpamError</span><span class="p">,</span> <span class="s">"System command failed"</span><span class="p">);</span>
<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">return</span> <span class="n">PyLong_FromLong</span><span class="p">(</span><span class="n">sts</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="back-to-the-example">
<span id="backtoexample"></span><h2>1.3. Back to the Example<a class="headerlink" href="#back-to-the-example" title="本標題的永久連結">¶</a></h2>
<p>Going back to our example function, you should now be able to understand this
statement:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">"s"</span><span class="p">,</span> <span class="o">&</span><span class="n">command</span><span class="p">))</span>
<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
</pre></div>
</div>
<p>It returns <em>NULL</em> (the error indicator for functions returning object pointers)
if an error is detected in the argument list, relying on the exception set by
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>. Otherwise the string value of the argument has been
copied to the local variable <code class="xref c c-data docutils literal notranslate"><span class="pre">command</span></code>. This is a pointer assignment and
you are not supposed to modify the string to which it points (so in Standard C,
the variable <code class="xref c c-data docutils literal notranslate"><span class="pre">command</span></code> should properly be declared as <code class="docutils literal notranslate"><span class="pre">const</span> <span class="pre">char</span>
<span class="pre">*command</span></code>).</p>
<p>The next statement is a call to the Unix function <code class="xref c c-func docutils literal notranslate"><span class="pre">system()</span></code>, passing it
the string we just got from <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">sts</span> <span class="o">=</span> <span class="n">system</span><span class="p">(</span><span class="n">command</span><span class="p">);</span>
</pre></div>
</div>
<p>Our <code class="xref py py-func docutils literal notranslate"><span class="pre">spam.system()</span></code> function must return the value of <code class="xref c c-data docutils literal notranslate"><span class="pre">sts</span></code> as a
Python object. This is done using the function <a class="reference internal" href="../c-api/long.html#c.PyLong_FromLong" title="PyLong_FromLong"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyLong_FromLong()</span></code></a>.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">return</span> <span class="nf">PyLong_FromLong</span><span class="p">(</span><span class="n">sts</span><span class="p">);</span>
</pre></div>
</div>
<p>In this case, it will return an integer object. (Yes, even integers are objects
on the heap in Python!)</p>
<p>If you have a C function that returns no useful argument (a function returning
<code class="xref c c-type docutils literal notranslate"><span class="pre">void</span></code>), the corresponding Python function must return <code class="docutils literal notranslate"><span class="pre">None</span></code>. You
need this idiom to do so (which is implemented by the <a class="reference internal" href="../c-api/none.html#c.Py_RETURN_NONE" title="Py_RETURN_NONE"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_RETURN_NONE</span></code></a>
macro):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Py_INCREF</span><span class="p">(</span><span class="n">Py_None</span><span class="p">);</span>
<span class="k">return</span> <span class="n">Py_None</span><span class="p">;</span>
</pre></div>
</div>
<p><a class="reference internal" href="../c-api/none.html#c.Py_None" title="Py_None"><code class="xref c c-data docutils literal notranslate"><span class="pre">Py_None</span></code></a> is the C name for the special Python object <code class="docutils literal notranslate"><span class="pre">None</span></code>. It is a
genuine Python object rather than a <em>NULL</em> pointer, which means 「error」 in most
contexts, as we have seen.</p>
</div>
<div class="section" id="the-module-s-method-table-and-initialization-function">
<span id="methodtable"></span><h2>1.4. The Module’s Method Table and Initialization Function<a class="headerlink" href="#the-module-s-method-table-and-initialization-function" title="本標題的永久連結">¶</a></h2>
<p>I promised to show how <code class="xref c c-func docutils literal notranslate"><span class="pre">spam_system()</span></code> is called from Python programs.
First, we need to list its name and address in a 「method table」:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">SpamMethods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
<span class="p">...</span>
<span class="p">{</span><span class="s">"system"</span><span class="p">,</span> <span class="n">spam_system</span><span class="p">,</span> <span class="n">METH_VARARGS</span><span class="p">,</span>
<span class="s">"Execute a shell command."</span><span class="p">},</span>
<span class="p">...</span>
<span class="p">{</span><span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">}</span> <span class="cm">/* Sentinel */</span>
<span class="p">};</span>
</pre></div>
</div>
<p>Note the third entry (<code class="docutils literal notranslate"><span class="pre">METH_VARARGS</span></code>). This is a flag telling the interpreter
the calling convention to be used for the C function. It should normally always
be <code class="docutils literal notranslate"><span class="pre">METH_VARARGS</span></code> or <code class="docutils literal notranslate"><span class="pre">METH_VARARGS</span> <span class="pre">|</span> <span class="pre">METH_KEYWORDS</span></code>; a value of <code class="docutils literal notranslate"><span class="pre">0</span></code> means
that an obsolete variant of <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> is used.</p>
<p>When using only <code class="docutils literal notranslate"><span class="pre">METH_VARARGS</span></code>, the function should expect the Python-level
parameters to be passed in as a tuple acceptable for parsing via
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>; more information on this function is provided below.</p>
<p>The <a class="reference internal" href="../c-api/structures.html#METH_KEYWORDS" title="METH_KEYWORDS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_KEYWORDS</span></code></a> bit may be set in the third field if keyword
arguments should be passed to the function. In this case, the C function should
accept a third <code class="docutils literal notranslate"><span class="pre">PyObject</span> <span class="pre">*</span></code> parameter which will be a dictionary of keywords.
Use <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTupleAndKeywords()</span></code></a> to parse the arguments to such a
function.</p>
<p>The method table must be referenced in the module definition structure:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="k">struct</span> <span class="n">PyModuleDef</span> <span class="n">spammodule</span> <span class="o">=</span> <span class="p">{</span>
<span class="n">PyModuleDef_HEAD_INIT</span><span class="p">,</span>
<span class="s">"spam"</span><span class="p">,</span> <span class="cm">/* name of module */</span>
<span class="n">spam_doc</span><span class="p">,</span> <span class="cm">/* module documentation, may be NULL */</span>
<span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="cm">/* size of per-interpreter state of the module,</span>
<span class="cm"> or -1 if the module keeps state in global variables. */</span>
<span class="n">SpamMethods</span>
<span class="p">};</span>
</pre></div>
</div>
<p>This structure, in turn, must be passed to the interpreter in the module’s
initialization function. The initialization function must be named
<code class="xref c c-func docutils literal notranslate"><span class="pre">PyInit_name()</span></code>, where <em>name</em> is the name of the module, and should be the
only non-<code class="docutils literal notranslate"><span class="pre">static</span></code> item defined in the module file:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyMODINIT_FUNC</span>
<span class="nf">PyInit_spam</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">PyModule_Create</span><span class="p">(</span><span class="o">&</span><span class="n">spammodule</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Note that PyMODINIT_FUNC declares the function as <code class="docutils literal notranslate"><span class="pre">PyObject</span> <span class="pre">*</span></code> return type,
declares any special linkage declarations required by the platform, and for C++
declares the function as <code class="docutils literal notranslate"><span class="pre">extern</span> <span class="pre">"C"</span></code>.</p>
<p>When the Python program imports module <code class="xref py py-mod docutils literal notranslate"><span class="pre">spam</span></code> for the first time,
<code class="xref c c-func docutils literal notranslate"><span class="pre">PyInit_spam()</span></code> is called. (See below for comments about embedding Python.)
It calls <a class="reference internal" href="../c-api/module.html#c.PyModule_Create" title="PyModule_Create"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyModule_Create()</span></code></a>, which returns a module object, and
inserts built-in function objects into the newly created module based upon the
table (an array of <a class="reference internal" href="../c-api/structures.html#c.PyMethodDef" title="PyMethodDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyMethodDef</span></code></a> structures) found in the module definition.
<a class="reference internal" href="../c-api/module.html#c.PyModule_Create" title="PyModule_Create"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyModule_Create()</span></code></a> returns a pointer to the module object
that it creates. It may abort with a fatal error for
certain errors, or return <em>NULL</em> if the module could not be initialized
satisfactorily. The init function must return the module object to its caller,
so that it then gets inserted into <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>.</p>
<p>When embedding Python, the <code class="xref c c-func docutils literal notranslate"><span class="pre">PyInit_spam()</span></code> function is not called
automatically unless there’s an entry in the <code class="xref c c-data docutils literal notranslate"><span class="pre">PyImport_Inittab</span></code> table.
To add the module to the initialization table, use <a class="reference internal" href="../c-api/import.html#c.PyImport_AppendInittab" title="PyImport_AppendInittab"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_AppendInittab()</span></code></a>,
optionally followed by an import of the module:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span>
<span class="nf">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">argv</span><span class="p">[])</span>
<span class="p">{</span>
<span class="kt">wchar_t</span> <span class="o">*</span><span class="n">program</span> <span class="o">=</span> <span class="n">Py_DecodeLocale</span><span class="p">(</span><span class="n">argv</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="nb">NULL</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="n">program</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
<span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">"Fatal error: cannot decode argv[0]</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
<span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
<span class="p">}</span>
<span class="cm">/* Add a built-in module, before Py_Initialize */</span>
<span class="n">PyImport_AppendInittab</span><span class="p">(</span><span class="s">"spam"</span><span class="p">,</span> <span class="n">PyInit_spam</span><span class="p">);</span>
<span class="cm">/* Pass argv[0] to the Python interpreter */</span>
<span class="n">Py_SetProgramName</span><span class="p">(</span><span class="n">program</span><span class="p">);</span>
<span class="cm">/* Initialize the Python interpreter. Required. */</span>
<span class="n">Py_Initialize</span><span class="p">();</span>
<span class="cm">/* Optionally import the module; alternatively,</span>
<span class="cm"> import can be deferred until the embedded script</span>
<span class="cm"> imports it. */</span>
<span class="n">PyImport_ImportModule</span><span class="p">(</span><span class="s">"spam"</span><span class="p">);</span>
<span class="p">...</span>
<span class="n">PyMem_RawFree</span><span class="p">(</span><span class="n">program</span><span class="p">);</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">備註</p>
<p class="last">Removing entries from <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> or importing compiled modules into
multiple interpreters within a process (or following a <code class="xref c c-func docutils literal notranslate"><span class="pre">fork()</span></code> without an
intervening <code class="xref c c-func docutils literal notranslate"><span class="pre">exec()</span></code>) can create problems for some extension modules.
Extension module authors should exercise caution when initializing internal data
structures.</p>
</div>
<p>A more substantial example module is included in the Python source distribution
as <code class="file docutils literal notranslate"><span class="pre">Modules/xxmodule.c</span></code>. This file may be used as a template or simply
read as an example.</p>
<div class="admonition note">
<p class="first admonition-title">備註</p>
<p class="last">Unlike our <code class="docutils literal notranslate"><span class="pre">spam</span></code> example, <code class="docutils literal notranslate"><span class="pre">xxmodule</span></code> uses <em>multi-phase initialization</em>
(new in Python 3.5), where a PyModuleDef structure is returned from
<code class="docutils literal notranslate"><span class="pre">PyInit_spam</span></code>, and creation of the module is left to the import machinery.
For details on multi-phase initialization, see <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0489"><strong>PEP 489</strong></a>.</p>
</div>
</div>
<div class="section" id="compilation-and-linkage">
<span id="compilation"></span><h2>1.5. Compilation and Linkage<a class="headerlink" href="#compilation-and-linkage" title="本標題的永久連結">¶</a></h2>
<p>There are two more things to do before you can use your new extension: compiling
and linking it with the Python system. If you use dynamic loading, the details
may depend on the style of dynamic loading your system uses; see the chapters
about building extension modules (chapter <a class="reference internal" href="building.html#building"><span class="std std-ref">Building C and C++ Extensions</span></a>) and additional
information that pertains only to building on Windows (chapter
<a class="reference internal" href="windows.html#building-on-windows"><span class="std std-ref">Building C and C++ Extensions on Windows</span></a>) for more information about this.</p>
<p>If you can’t use dynamic loading, or if you want to make your module a permanent
part of the Python interpreter, you will have to change the configuration setup
and rebuild the interpreter. Luckily, this is very simple on Unix: just place
your file (<code class="file docutils literal notranslate"><span class="pre">spammodule.c</span></code> for example) in the <code class="file docutils literal notranslate"><span class="pre">Modules/</span></code> directory
of an unpacked source distribution, add a line to the file
<code class="file docutils literal notranslate"><span class="pre">Modules/Setup.local</span></code> describing your file:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>spam spammodule.o
</pre></div>
</div>
<p>and rebuild the interpreter by running <strong class="program">make</strong> in the toplevel
directory. You can also run <strong class="program">make</strong> in the <code class="file docutils literal notranslate"><span class="pre">Modules/</span></code>
subdirectory, but then you must first rebuild <code class="file docutils literal notranslate"><span class="pre">Makefile</span></code> there by running
『<strong class="program">make</strong> Makefile』. (This is necessary each time you change the
<code class="file docutils literal notranslate"><span class="pre">Setup</span></code> file.)</p>
<p>If your module requires additional libraries to link with, these can be listed
on the line in the configuration file as well, for instance:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>spam spammodule.o -lX11
</pre></div>
</div>
</div>
<div class="section" id="calling-python-functions-from-c">
<span id="callingpython"></span><h2>1.6. Calling Python Functions from C<a class="headerlink" href="#calling-python-functions-from-c" title="本標題的永久連結">¶</a></h2>
<p>So far we have concentrated on making C functions callable from Python. The
reverse is also useful: calling Python functions from C. This is especially the
case for libraries that support so-called 「callback」 functions. If a C
interface makes use of callbacks, the equivalent Python often needs to provide a
callback mechanism to the Python programmer; the implementation will require
calling the Python callback functions from a C callback. Other uses are also
imaginable.</p>
<p>Fortunately, the Python interpreter is easily called recursively, and there is a
standard interface to call a Python function. (I won’t dwell on how to call the
Python parser with a particular string as input — if you’re interested, have a
look at the implementation of the <a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> command line option in
<code class="file docutils literal notranslate"><span class="pre">Modules/main.c</span></code> from the Python source code.)</p>
<p>Calling a Python function is easy. First, the Python program must somehow pass
you the Python function object. You should provide a function (or some other
interface) to do this. When this function is called, save a pointer to the
Python function object (be careful to <a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> it!) in a global
variable — or wherever you see fit. For example, the following function might
be part of a module definition:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">my_callback</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">my_set_callback</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">dummy</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">PyObject</span> <span class="o">*</span><span class="n">result</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="n">PyObject</span> <span class="o">*</span><span class="n">temp</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">"O:set_callback"</span><span class="p">,</span> <span class="o">&</span><span class="n">temp</span><span class="p">))</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyCallable_Check</span><span class="p">(</span><span class="n">temp</span><span class="p">))</span> <span class="p">{</span>
<span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_TypeError</span><span class="p">,</span> <span class="s">"parameter must be callable"</span><span class="p">);</span>
<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="p">}</span>
<span class="n">Py_XINCREF</span><span class="p">(</span><span class="n">temp</span><span class="p">);</span> <span class="cm">/* Add a reference to new callback */</span>
<span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">my_callback</span><span class="p">);</span> <span class="cm">/* Dispose of previous callback */</span>
<span class="n">my_callback</span> <span class="o">=</span> <span class="n">temp</span><span class="p">;</span> <span class="cm">/* Remember new callback */</span>
<span class="cm">/* Boilerplate to return "None" */</span>
<span class="n">Py_INCREF</span><span class="p">(</span><span class="n">Py_None</span><span class="p">);</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">Py_None</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">return</span> <span class="n">result</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This function must be registered with the interpreter using the
<a class="reference internal" href="../c-api/structures.html#METH_VARARGS" title="METH_VARARGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_VARARGS</span></code></a> flag; this is described in section <a class="reference internal" href="#methodtable"><span class="std std-ref">The Module’s Method Table and Initialization Function</span></a>. The
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> function and its arguments are documented in section
<a class="reference internal" href="#parsetuple"><span class="std std-ref">Extracting Parameters in Extension Functions</span></a>.</p>
<p>The macros <a class="reference internal" href="../c-api/refcounting.html#c.Py_XINCREF" title="Py_XINCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XINCREF()</span></code></a> and <a class="reference internal" href="../c-api/refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a> increment/decrement the
reference count of an object and are safe in the presence of <em>NULL</em> pointers
(but note that <em>temp</em> will not be <em>NULL</em> in this context). More info on them
in section <a class="reference internal" href="#refcounts"><span class="std std-ref">Reference Counts</span></a>.</p>
<p id="index-1">Later, when it is time to call the function, you call the C function
<a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a>. This function has two arguments, both pointers to
arbitrary Python objects: the Python function, and the argument list. The
argument list must always be a tuple object, whose length is the number of
arguments. To call the Python function with no arguments, pass in NULL, or
an empty tuple; to call it with one argument, pass a singleton tuple.
<a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> returns a tuple when its format string consists of zero
or more format codes between parentheses. For example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span> <span class="n">arg</span><span class="p">;</span>
<span class="n">PyObject</span> <span class="o">*</span><span class="n">arglist</span><span class="p">;</span>
<span class="n">PyObject</span> <span class="o">*</span><span class="n">result</span><span class="p">;</span>
<span class="p">...</span>
<span class="n">arg</span> <span class="o">=</span> <span class="mi">123</span><span class="p">;</span>
<span class="p">...</span>
<span class="cm">/* Time to call the callback */</span>
<span class="n">arglist</span> <span class="o">=</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">"(i)"</span><span class="p">,</span> <span class="n">arg</span><span class="p">);</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">PyObject_CallObject</span><span class="p">(</span><span class="n">my_callback</span><span class="p">,</span> <span class="n">arglist</span><span class="p">);</span>
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">arglist</span><span class="p">);</span>
</pre></div>
</div>
<p><a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> returns a Python object pointer: this is the return
value of the Python function. <a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> is
「reference-count-neutral」 with respect to its arguments. In the example a new
tuple was created to serve as the argument list, which is <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>-ed immediately after the <a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> call.</p>
<p>The return value of <a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> is 「new」: either it is a brand
new object, or it is an existing object whose reference count has been
incremented. So, unless you want to save it in a global variable, you should
somehow <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> the result, even (especially!) if you are not
interested in its value.</p>
<p>Before you do this, however, it is important to check that the return value
isn’t <em>NULL</em>. If it is, the Python function terminated by raising an exception.
If the C code that called <a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> is called from Python, it
should now return an error indication to its Python caller, so the interpreter
can print a stack trace, or the calling Python code can handle the exception.
If this is not possible or desirable, the exception should be cleared by calling
<a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Clear" title="PyErr_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Clear()</span></code></a>. For example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="n">result</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span> <span class="cm">/* Pass error back */</span>
<span class="p">...</span><span class="n">use</span> <span class="n">result</span><span class="p">...</span>
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">result</span><span class="p">);</span>
</pre></div>
</div>
<p>Depending on the desired interface to the Python callback function, you may also
have to provide an argument list to <a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a>. In some cases
the argument list is also provided by the Python program, through the same
interface that specified the callback function. It can then be saved and used
in the same manner as the function object. In other cases, you may have to
construct a new tuple to pass as the argument list. The simplest way to do this
is to call <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>. For example, if you want to pass an integral
event code, you might use the following code:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">arglist</span><span class="p">;</span>
<span class="p">...</span>
<span class="n">arglist</span> <span class="o">=</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">"(l)"</span><span class="p">,</span> <span class="n">eventcode</span><span class="p">);</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">PyObject_CallObject</span><span class="p">(</span><span class="n">my_callback</span><span class="p">,</span> <span class="n">arglist</span><span class="p">);</span>
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">arglist</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="n">result</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span> <span class="cm">/* Pass error back */</span>
<span class="cm">/* Here maybe use the result */</span>
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">result</span><span class="p">);</span>
</pre></div>
</div>
<p>Note the placement of <code class="docutils literal notranslate"><span class="pre">Py_DECREF(arglist)</span></code> immediately after the call, before
the error check! Also note that strictly speaking this code is not complete:
<a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> may run out of memory, and this should be checked.</p>
<p>You may also call a function with keyword arguments by using
<a class="reference internal" href="../c-api/object.html#c.PyObject_Call" title="PyObject_Call"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Call()</span></code></a>, which supports arguments and keyword arguments. As in
the above example, we use <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> to construct the dictionary.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">dict</span><span class="p">;</span>
<span class="p">...</span>
<span class="n">dict</span> <span class="o">=</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">"{s:i}"</span><span class="p">,</span> <span class="s">"name"</span><span class="p">,</span> <span class="n">val</span><span class="p">);</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">PyObject_Call</span><span class="p">(</span><span class="n">my_callback</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="n">dict</span><span class="p">);</span>
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">dict</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="n">result</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span> <span class="cm">/* Pass error back */</span>
<span class="cm">/* Here maybe use the result */</span>
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">result</span><span class="p">);</span>
</pre></div>
</div>
</div>
<div class="section" id="extracting-parameters-in-extension-functions">
<span id="parsetuple"></span><h2>1.7. Extracting Parameters in Extension Functions<a class="headerlink" href="#extracting-parameters-in-extension-functions" title="本標題的永久連結">¶</a></h2>
<p id="index-2">The <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> function is declared as follows:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span> <span class="nf">PyArg_ParseTuple</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">arg</span><span class="p">,</span> <span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">format</span><span class="p">,</span> <span class="p">...);</span>
</pre></div>
</div>
<p>The <em>arg</em> argument must be a tuple object containing an argument list passed
from Python to a C function. The <em>format</em> argument must be a format string,
whose syntax is explained in <a class="reference internal" href="../c-api/arg.html#arg-parsing"><span class="std std-ref">Parsing arguments and building values</span></a> in the Python/C API Reference
Manual. The remaining arguments must be addresses of variables whose type is
determined by the format string.</p>
<p>Note that while <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> checks that the Python arguments have
the required types, it cannot check the validity of the addresses of C variables
passed to the call: if you make mistakes there, your code will probably crash or
at least overwrite random bits in memory. So be careful!</p>
<p>Note that any Python object references which are provided to the caller are
<em>borrowed</em> references; do not decrement their reference count!</p>
<p>Some example calls:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#define PY_SSIZE_T_CLEAN </span><span class="cm">/* Make "s#" use Py_ssize_t rather than int. */</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf"><Python.h></span><span class="cp"></span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span> <span class="n">ok</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">i</span><span class="p">,</span> <span class="n">j</span><span class="p">;</span>
<span class="kt">long</span> <span class="n">k</span><span class="p">,</span> <span class="n">l</span><span class="p">;</span>
<span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">s</span><span class="p">;</span>
<span class="n">Py_ssize_t</span> <span class="n">size</span><span class="p">;</span>
<span class="n">ok</span> <span class="o">=</span> <span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">""</span><span class="p">);</span> <span class="cm">/* No arguments */</span>
<span class="cm">/* Python call: f() */</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">ok</span> <span class="o">=</span> <span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">"s"</span><span class="p">,</span> <span class="o">&</span><span class="n">s</span><span class="p">);</span> <span class="cm">/* A string */</span>
<span class="cm">/* Possible Python call: f('whoops!') */</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">ok</span> <span class="o">=</span> <span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">"lls"</span><span class="p">,</span> <span class="o">&</span><span class="n">k</span><span class="p">,</span> <span class="o">&</span><span class="n">l</span><span class="p">,</span> <span class="o">&</span><span class="n">s</span><span class="p">);</span> <span class="cm">/* Two longs and a string */</span>
<span class="cm">/* Possible Python call: f(1, 2, 'three') */</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">ok</span> <span class="o">=</span> <span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">"(ii)s#"</span><span class="p">,</span> <span class="o">&</span><span class="n">i</span><span class="p">,</span> <span class="o">&</span><span class="n">j</span><span class="p">,</span> <span class="o">&</span><span class="n">s</span><span class="p">,</span> <span class="o">&</span><span class="n">size</span><span class="p">);</span>
<span class="cm">/* A pair of ints and a string, whose size is also returned */</span>
<span class="cm">/* Possible Python call: f((1, 2), 'three') */</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="p">{</span>
<span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">file</span><span class="p">;</span>
<span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">mode</span> <span class="o">=</span> <span class="s">"r"</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">bufsize</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="n">ok</span> <span class="o">=</span> <span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">"s|si"</span><span class="p">,</span> <span class="o">&</span><span class="n">file</span><span class="p">,</span> <span class="o">&</span><span class="n">mode</span><span class="p">,</span> <span class="o">&</span><span class="n">bufsize</span><span class="p">);</span>
<span class="cm">/* A string, and optionally another string and an integer */</span>
<span class="cm">/* Possible Python calls:</span>
<span class="cm"> f('spam')</span>
<span class="cm"> f('spam', 'w')</span>
<span class="cm"> f('spam', 'wb', 100000) */</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="p">{</span>
<span class="kt">int</span> <span class="n">left</span><span class="p">,</span> <span class="n">top</span><span class="p">,</span> <span class="n">right</span><span class="p">,</span> <span class="n">bottom</span><span class="p">,</span> <span class="n">h</span><span class="p">,</span> <span class="n">v</span><span class="p">;</span>
<span class="n">ok</span> <span class="o">=</span> <span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">"((ii)(ii))(ii)"</span><span class="p">,</span>
<span class="o">&</span><span class="n">left</span><span class="p">,</span> <span class="o">&</span><span class="n">top</span><span class="p">,</span> <span class="o">&</span><span class="n">right</span><span class="p">,</span> <span class="o">&</span><span class="n">bottom</span><span class="p">,</span> <span class="o">&</span><span class="n">h</span><span class="p">,</span> <span class="o">&</span><span class="n">v</span><span class="p">);</span>
<span class="cm">/* A rectangle and a point */</span>
<span class="cm">/* Possible Python call:</span>
<span class="cm"> f(((0, 0), (400, 300)), (10, 10)) */</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="p">{</span>
<span class="n">Py_complex</span> <span class="n">c</span><span class="p">;</span>
<span class="n">ok</span> <span class="o">=</span> <span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">"D:myfunction"</span><span class="p">,</span> <span class="o">&</span><span class="n">c</span><span class="p">);</span>
<span class="cm">/* a complex, also providing a function name for errors */</span>
<span class="cm">/* Possible Python call: myfunction(1+2j) */</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="keyword-parameters-for-extension-functions">
<span id="parsetupleandkeywords"></span><h2>1.8. Keyword Parameters for Extension Functions<a class="headerlink" href="#keyword-parameters-for-extension-functions" title="本標題的永久連結">¶</a></h2>
<p id="index-3">The <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTupleAndKeywords()</span></code></a> function is declared as follows:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span> <span class="nf">PyArg_ParseTupleAndKeywords</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">arg</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwdict</span><span class="p">,</span>
<span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">format</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">kwlist</span><span class="p">[],</span> <span class="p">...);</span>
</pre></div>
</div>
<p>The <em>arg</em> and <em>format</em> parameters are identical to those of the
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> function. The <em>kwdict</em> parameter is the dictionary of
keywords received as the third parameter from the Python runtime. The <em>kwlist</em>
parameter is a <em>NULL</em>-terminated list of strings which identify the parameters;
the names are matched with the type information from <em>format</em> from left to
right. On success, <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTupleAndKeywords()</span></code></a> returns true, otherwise
it returns false and raises an appropriate exception.</p>
<div class="admonition note">
<p class="first admonition-title">備註</p>
<p class="last">Nested tuples cannot be parsed when using keyword arguments! Keyword parameters
passed in which are not present in the <em>kwlist</em> will cause <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> to
be raised.</p>
</div>
<p id="index-4">Here is an example module which uses keywords, based on an example by Geoff
Philbrick (<a class="reference external" href="mailto:philbrick%40hks.com">philbrick<span>@</span>hks<span>.</span>com</a>):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">"Python.h"</span><span class="cp"></span>
<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">keywdarg_parrot</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">keywds</span><span class="p">)</span>
<span class="p">{</span>
<span class="kt">int</span> <span class="n">voltage</span><span class="p">;</span>
<span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">state</span> <span class="o">=</span> <span class="s">"a stiff"</span><span class="p">;</span>
<span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">action</span> <span class="o">=</span> <span class="s">"voom"</span><span class="p">;</span>
<span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">type</span> <span class="o">=</span> <span class="s">"Norwegian Blue"</span><span class="p">;</span>
<span class="k">static</span> <span class="kt">char</span> <span class="o">*</span><span class="n">kwlist</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span><span class="s">"voltage"</span><span class="p">,</span> <span class="s">"state"</span><span class="p">,</span> <span class="s">"action"</span><span class="p">,</span> <span class="s">"type"</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">};</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTupleAndKeywords</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="n">keywds</span><span class="p">,</span> <span class="s">"i|sss"</span><span class="p">,</span> <span class="n">kwlist</span><span class="p">,</span>
<span class="o">&</span><span class="n">voltage</span><span class="p">,</span> <span class="o">&</span><span class="n">state</span><span class="p">,</span> <span class="o">&</span><span class="n">action</span><span class="p">,</span> <span class="o">&</span><span class="n">type</span><span class="p">))</span>
<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="n">printf</span><span class="p">(</span><span class="s">"-- This parrot wouldn't %s if you put %i Volts through it.</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span>
<span class="n">action</span><span class="p">,</span> <span class="n">voltage</span><span class="p">);</span>
<span class="n">printf</span><span class="p">(</span><span class="s">"-- Lovely plumage, the %s -- It's %s!</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">type</span><span class="p">,</span> <span class="n">state</span><span class="p">);</span>
<span class="n">Py_RETURN_NONE</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">keywdarg_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
<span class="cm">/* The cast of the function is necessary since PyCFunction values</span>
<span class="cm"> * only take two PyObject* parameters, and keywdarg_parrot() takes</span>
<span class="cm"> * three.</span>
<span class="cm"> */</span>
<span class="p">{</span><span class="s">"parrot"</span><span class="p">,</span> <span class="p">(</span><span class="n">PyCFunction</span><span class="p">)</span><span class="n">keywdarg_parrot</span><span class="p">,</span> <span class="n">METH_VARARGS</span> <span class="o">|</span> <span class="n">METH_KEYWORDS</span><span class="p">,</span>
<span class="s">"Print a lovely skit to standard output."</span><span class="p">},</span>
<span class="p">{</span><span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">}</span> <span class="cm">/* sentinel */</span>
<span class="p">};</span>
<span class="k">static</span> <span class="k">struct</span> <span class="n">PyModuleDef</span> <span class="n">keywdargmodule</span> <span class="o">=</span> <span class="p">{</span>
<span class="n">PyModuleDef_HEAD_INIT</span><span class="p">,</span>
<span class="s">"keywdarg"</span><span class="p">,</span>
<span class="nb">NULL</span><span class="p">,</span>
<span class="o">-</span><span class="mi">1</span><span class="p">,</span>
<span class="n">keywdarg_methods</span>
<span class="p">};</span>
<span class="n">PyMODINIT_FUNC</span>
<span class="nf">PyInit_keywdarg</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">PyModule_Create</span><span class="p">(</span><span class="o">&</span><span class="n">keywdargmodule</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="building-arbitrary-values">
<span id="buildvalue"></span><h2>1.9. Building Arbitrary Values<a class="headerlink" href="#building-arbitrary-values" title="本標題的永久連結">¶</a></h2>
<p>This function is the counterpart to <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>. It is declared
as follows:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="nf">Py_BuildValue</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">format</span><span class="p">,</span> <span class="p">...);</span>
</pre></div>
</div>
<p>It recognizes a set of format units similar to the ones recognized by
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>, but the arguments (which are input to the function,
not output) must not be pointers, just values. It returns a new Python object,
suitable for returning from a C function called from Python.</p>
<p>One difference with <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>: while the latter requires its
first argument to be a tuple (since Python argument lists are always represented
as tuples internally), <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> does not always build a tuple. It
builds a tuple only if its format string contains two or more format units. If
the format string is empty, it returns <code class="docutils literal notranslate"><span class="pre">None</span></code>; if it contains exactly one
format unit, it returns whatever object is described by that format unit. To
force it to return a tuple of size 0 or one, parenthesize the format string.</p>
<p>Examples (to the left the call, to the right the resulting Python value):</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Py_BuildValue("") None
Py_BuildValue("i", 123) 123
Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)
Py_BuildValue("s", "hello") 'hello'
Py_BuildValue("y", "hello") b'hello'
Py_BuildValue("ss", "hello", "world") ('hello', 'world')
Py_BuildValue("s#", "hello", 4) 'hell'
Py_BuildValue("y#", "hello", 4) b'hell'
Py_BuildValue("()") ()
Py_BuildValue("(i)", 123) (123,)
Py_BuildValue("(ii)", 123, 456) (123, 456)
Py_BuildValue("(i,i)", 123, 456) (123, 456)
Py_BuildValue("[i,i]", 123, 456) [123, 456]
Py_BuildValue("{s:i,s:i}",
"abc", 123, "def", 456) {'abc': 123, 'def': 456}
Py_BuildValue("((ii)(ii)) (ii)",
1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))
</pre></div>
</div>
</div>
<div class="section" id="reference-counts">
<span id="refcounts"></span><h2>1.10. Reference Counts<a class="headerlink" href="#reference-counts" title="本標題的永久連結">¶</a></h2>
<p>In languages like C or C++, the programmer is responsible for dynamic allocation
and deallocation of memory on the heap. In C, this is done using the functions
<code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>. In C++, the operators <code class="docutils literal notranslate"><span class="pre">new</span></code> and
<code class="docutils literal notranslate"><span class="pre">delete</span></code> are used with essentially the same meaning and we’ll restrict
the following discussion to the C case.</p>
<p>Every block of memory allocated with <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> should eventually be
returned to the pool of available memory by exactly one call to <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>.
It is important to call <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> at the right time. If a block’s address
is forgotten but <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> is not called for it, the memory it occupies
cannot be reused until the program terminates. This is called a <em class="dfn">memory
leak</em>. On the other hand, if a program calls <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> for a block and then
continues to use the block, it creates a conflict with re-use of the block
through another <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> call. This is called <em class="dfn">using freed memory</em>.
It has the same bad consequences as referencing uninitialized data — core
dumps, wrong results, mysterious crashes.</p>
<p>Common causes of memory leaks are unusual paths through the code. For instance,
a function may allocate a block of memory, do some calculation, and then free
the block again. Now a change in the requirements for the function may add a
test to the calculation that detects an error condition and can return
prematurely from the function. It’s easy to forget to free the allocated memory
block when taking this premature exit, especially when it is added later to the
code. Such leaks, once introduced, often go undetected for a long time: the
error exit is taken only in a small fraction of all calls, and most modern
machines have plenty of virtual memory, so the leak only becomes apparent in a
long-running process that uses the leaking function frequently. Therefore, it’s
important to prevent leaks from happening by having a coding convention or
strategy that minimizes this kind of errors.</p>
<p>Since Python makes heavy use of <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>, it needs a
strategy to avoid memory leaks as well as the use of freed memory. The chosen
method is called <em class="dfn">reference counting</em>. The principle is simple: every
object contains a counter, which is incremented when a reference to the object
is stored somewhere, and which is decremented when a reference to it is deleted.
When the counter reaches zero, the last reference to the object has been deleted
and the object is freed.</p>
<p>An alternative strategy is called <em class="dfn">automatic garbage collection</em>.
(Sometimes, reference counting is also referred to as a garbage collection
strategy, hence my use of 「automatic」 to distinguish the two.) The big
advantage of automatic garbage collection is that the user doesn’t need to call
<code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> explicitly. (Another claimed advantage is an improvement in speed
or memory usage — this is no hard fact however.) The disadvantage is that for
C, there is no truly portable automatic garbage collector, while reference
counting can be implemented portably (as long as the functions <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code>
and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> are available — which the C Standard guarantees). Maybe some
day a sufficiently portable automatic garbage collector will be available for C.
Until then, we’ll have to live with reference counts.</p>
<p>While Python uses the traditional reference counting implementation, it also
offers a cycle detector that works to detect reference cycles. This allows
applications to not worry about creating direct or indirect circular references;
these are the weakness of garbage collection implemented using only reference
counting. Reference cycles consist of objects which contain (possibly indirect)
references to themselves, so that each object in the cycle has a reference count
which is non-zero. Typical reference counting implementations are not able to
reclaim the memory belonging to any objects in a reference cycle, or referenced
from the objects in the cycle, even though there are no further references to
the cycle itself.</p>
<p>The cycle detector is able to detect garbage cycles and can reclaim them.
The <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module exposes a way to run the detector (the
<a class="reference internal" href="../library/gc.html#gc.collect" title="gc.collect"><code class="xref py py-func docutils literal notranslate"><span class="pre">collect()</span></code></a> function), as well as configuration
interfaces and the ability to disable the detector at runtime. The cycle
detector is considered an optional component; though it is included by default,
it can be disabled at build time using the <code class="xref std std-option docutils literal notranslate"><span class="pre">--without-cycle-gc</span></code> option
to the <strong class="program">configure</strong> script on Unix platforms (including Mac OS X). If
the cycle detector is disabled in this way, the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module will not be
available.</p>
<div class="section" id="reference-counting-in-python">
<span id="refcountsinpython"></span><h3>1.10.1. Reference Counting in Python<a class="headerlink" href="#reference-counting-in-python" title="本標題的永久連結">¶</a></h3>
<p>There are two macros, <code class="docutils literal notranslate"><span class="pre">Py_INCREF(x)</span></code> and <code class="docutils literal notranslate"><span class="pre">Py_DECREF(x)</span></code>, which handle the
incrementing and decrementing of the reference count. <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> also
frees the object when the count reaches zero. For flexibility, it doesn’t call
<code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> directly — rather, it makes a call through a function pointer in
the object’s <em class="dfn">type object</em>. For this purpose (and others), every object
also contains a pointer to its type object.</p>
<p>The big question now remains: when to use <code class="docutils literal notranslate"><span class="pre">Py_INCREF(x)</span></code> and <code class="docutils literal notranslate"><span class="pre">Py_DECREF(x)</span></code>?
Let’s first introduce some terms. Nobody 「owns」 an object; however, you can
<em class="dfn">own a reference</em> to an object. An object’s reference count is now defined
as the number of owned references to it. The owner of a reference is
responsible for calling <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> when the reference is no longer
needed. Ownership of a reference can be transferred. There are three ways to
dispose of an owned reference: pass it on, store it, or call <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>.
Forgetting to dispose of an owned reference creates a memory leak.</p>
<p>It is also possible to <em class="dfn">borrow</em> <a class="footnote-reference" href="#id6" id="id2">[2]</a> a reference to an object. The
borrower of a reference should not call <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>. The borrower must
not hold on to the object longer than the owner from which it was borrowed.
Using a borrowed reference after the owner has disposed of it risks using freed
memory and should be avoided completely <a class="footnote-reference" href="#id7" id="id3">[3]</a>.</p>
<p>The advantage of borrowing over owning a reference is that you don’t need to
take care of disposing of the reference on all possible paths through the code
— in other words, with a borrowed reference you don’t run the risk of leaking
when a premature exit is taken. The disadvantage of borrowing over owning is
that there are some subtle situations where in seemingly correct code a borrowed
reference can be used after the owner from which it was borrowed has in fact
disposed of it.</p>
<p>A borrowed reference can be changed into an owned reference by calling
<a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a>. This does not affect the status of the owner from which the
reference was borrowed — it creates a new owned reference, and gives full
owner responsibilities (the new owner must dispose of the reference properly, as
well as the previous owner).</p>
</div>
<div class="section" id="ownership-rules">
<span id="ownershiprules"></span><h3>1.10.2. Ownership Rules<a class="headerlink" href="#ownership-rules" title="本標題的永久連結">¶</a></h3>
<p>Whenever an object reference is passed into or out of a function, it is part of
the function’s interface specification whether ownership is transferred with the
reference or not.</p>
<p>Most functions that return a reference to an object pass on ownership with the
reference. In particular, all functions whose function it is to create a new
object, such as <a class="reference internal" href="../c-api/long.html#c.PyLong_FromLong" title="PyLong_FromLong"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyLong_FromLong()</span></code></a> and <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>, pass
ownership to the receiver. Even if the object is not actually new, you still
receive ownership of a new reference to that object. For instance,
<a class="reference internal" href="../c-api/long.html#c.PyLong_FromLong" title="PyLong_FromLong"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyLong_FromLong()</span></code></a> maintains a cache of popular values and can return a
reference to a cached item.</p>
<p>Many functions that extract objects from other objects also transfer ownership
with the reference, for instance <a class="reference internal" href="../c-api/object.html#c.PyObject_GetAttrString" title="PyObject_GetAttrString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetAttrString()</span></code></a>. The picture
is less clear, here, however, since a few common routines are exceptions:
<a class="reference internal" href="../c-api/tuple.html#c.PyTuple_GetItem" title="PyTuple_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_GetItem()</span></code></a>, <a class="reference internal" href="../c-api/list.html#c.PyList_GetItem" title="PyList_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_GetItem()</span></code></a>, <a class="reference internal" href="../c-api/dict.html#c.PyDict_GetItem" title="PyDict_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyDict_GetItem()</span></code></a>, and
<a class="reference internal" href="../c-api/dict.html#c.PyDict_GetItemString" title="PyDict_GetItemString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyDict_GetItemString()</span></code></a> all return references that you borrow from the
tuple, list or dictionary.</p>
<p>The function <a class="reference internal" href="../c-api/import.html#c.PyImport_AddModule" title="PyImport_AddModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_AddModule()</span></code></a> also returns a borrowed reference, even
though it may actually create the object it returns: this is possible because an
owned reference to the object is stored in <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>.</p>
<p>When you pass an object reference into another function, in general, the
function borrows the reference from you — if it needs to store it, it will use
<a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> to become an independent owner. There are exactly two
important exceptions to this rule: <a class="reference internal" href="../c-api/tuple.html#c.PyTuple_SetItem" title="PyTuple_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_SetItem()</span></code></a> and
<a class="reference internal" href="../c-api/list.html#c.PyList_SetItem" title="PyList_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_SetItem()</span></code></a>. These functions take over ownership of the item passed
to them — even if they fail! (Note that <a class="reference internal" href="../c-api/dict.html#c.PyDict_SetItem" title="PyDict_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyDict_SetItem()</span></code></a> and friends
don’t take over ownership — they are 「normal.」)</p>
<p>When a C function is called from Python, it borrows references to its arguments
from the caller. The caller owns a reference to the object, so the borrowed
reference’s lifetime is guaranteed until the function returns. Only when such a
borrowed reference must be stored or passed on, it must be turned into an owned
reference by calling <a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a>.</p>
<p>The object reference returned from a C function that is called from Python must
be an owned reference — ownership is transferred from the function to its
caller.</p>
</div>
<div class="section" id="thin-ice">
<span id="thinice"></span><h3>1.10.3. Thin Ice<a class="headerlink" href="#thin-ice" title="本標題的永久連結">¶</a></h3>
<p>There are a few situations where seemingly harmless use of a borrowed reference
can lead to problems. These all have to do with implicit invocations of the
interpreter, which can cause the owner of a reference to dispose of it.</p>
<p>The first and most important case to know about is using <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> on
an unrelated object while borrowing a reference to a list item. For instance:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">void</span>
<span class="nf">bug</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">list</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span> <span class="o">=</span> <span class="n">PyList_GetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
<span class="n">PyList_SetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">PyLong_FromLong</span><span class="p">(</span><span class="mi">0L</span><span class="p">));</span>
<span class="n">PyObject_Print</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="n">stdout</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span> <span class="cm">/* BUG! */</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This function first borrows a reference to <code class="docutils literal notranslate"><span class="pre">list[0]</span></code>, then replaces
<code class="docutils literal notranslate"><span class="pre">list[1]</span></code> with the value <code class="docutils literal notranslate"><span class="pre">0</span></code>, and finally prints the borrowed reference.
Looks harmless, right? But it’s not!</p>
<p>Let’s follow the control flow into <a class="reference internal" href="../c-api/list.html#c.PyList_SetItem" title="PyList_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_SetItem()</span></code></a>. The list owns
references to all its items, so when item 1 is replaced, it has to dispose of
the original item 1. Now let’s suppose the original item 1 was an instance of a
user-defined class, and let’s further suppose that the class defined a
<a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method. If this class instance has a reference count of 1,
disposing of it will call its <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method.</p>
<p>Since it is written in Python, the <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method can execute arbitrary
Python code. Could it perhaps do something to invalidate the reference to
<code class="docutils literal notranslate"><span class="pre">item</span></code> in <code class="xref c c-func docutils literal notranslate"><span class="pre">bug()</span></code>? You bet! Assuming that the list passed into
<code class="xref c c-func docutils literal notranslate"><span class="pre">bug()</span></code> is accessible to the <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method, it could execute a
statement to the effect of <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">list[0]</span></code>, and assuming this was the last
reference to that object, it would free the memory associated with it, thereby
invalidating <code class="docutils literal notranslate"><span class="pre">item</span></code>.</p>
<p>The solution, once you know the source of the problem, is easy: temporarily
increment the reference count. The correct version of the function reads:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">void</span>
<span class="nf">no_bug</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">list</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span> <span class="o">=</span> <span class="n">PyList_GetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
<span class="n">Py_INCREF</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
<span class="n">PyList_SetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">PyLong_FromLong</span><span class="p">(</span><span class="mi">0L</span><span class="p">));</span>
<span class="n">PyObject_Print</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="n">stdout</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This is a true story. An older version of Python contained variants of this bug
and someone spent a considerable amount of time in a C debugger to figure out
why his <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods would fail…</p>
<p>The second case of problems with a borrowed reference is a variant involving
threads. Normally, multiple threads in the Python interpreter can’t get in each
other’s way, because there is a global lock protecting Python’s entire object
space. However, it is possible to temporarily release this lock using the macro
<a class="reference internal" href="../c-api/init.html#c.Py_BEGIN_ALLOW_THREADS" title="Py_BEGIN_ALLOW_THREADS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_BEGIN_ALLOW_THREADS</span></code></a>, and to re-acquire it using
<a class="reference internal" href="../c-api/init.html#c.Py_END_ALLOW_THREADS" title="Py_END_ALLOW_THREADS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_END_ALLOW_THREADS</span></code></a>. This is common around blocking I/O calls, to
let other threads use the processor while waiting for the I/O to complete.
Obviously, the following function has the same problem as the previous one:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">void</span>
<span class="nf">bug</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">list</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span> <span class="o">=</span> <span class="n">PyList_GetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
<span class="n">Py_BEGIN_ALLOW_THREADS</span>
<span class="p">...</span><span class="n">some</span> <span class="n">blocking</span> <span class="n">I</span><span class="o">/</span><span class="n">O</span> <span class="n">call</span><span class="p">...</span>