📄 257.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<META NAME="Robots" content="INDEX,NOFOLLOW">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<TITLE>Safari | Python Developer's Handbook -> Python/C API</TITLE>
<LINK REL="stylesheet" HREF="oreillyi/oreillyN.css">
</HEAD>
<BODY bgcolor="white" text="black" link="#990000" vlink="#990000" alink="#990000" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table width="100%" cellpadding=5 cellspacing=0 border=0 class="navtopbg"><tr><td><font size="1"><p class="navtitle"><a href="8.html" class="navtitle">Web Development</a> > <a href="0672319942.html" class="navtitle">Python Developer's Handbook</a> > <a href="255.html" class="navtitle">A. Python/C API</a> > <span class="nonavtitle">Python/C API</span></p></font></td><td align="right" valign="top" nowrap><font size="1"><a href="main.asp?list" class="safnavoff">See All Titles</a></font></td></tr></table>
<TABLE width=100% bgcolor=white border=0 cellspacing=0 cellpadding=5><TR><TD>
<TABLE border=0 width="100%" cellspacing=0 cellpadding=0><TR><td align=left width="15%" class="headingsubbarbg"><a href="256.html" title="A. Python/C API"><font size="1">< BACK</font></a></td><td align=center width="70%" class="headingsubbarbg"><font size="1"><a href="popanote.asp?pubui=oreilly&bookname=0672319942&snode=257" target="_blank" title="Make a public or private annnotation">Make Note</a> | <a href="257.html" title="Use a Safari bookmark to remember this section">Bookmark</a></font></td><td align=right width="15%" class="headingsubbarbg"><a href="258.html" title="The Very High Level Layer"><font size="1">CONTINUE ></font></a></td></TR></TABLE>
<a href="6%2F1%2F2002+6%3A27%3A44+PM.html" TABINDEX="-1"><img src=images/spacer.gif border=0 width=1 height=1></a><font color=white size=1>152015024128143245168232148039196038240039088173205162105045222218071088187087116113144</font><a href="read4.asp?bookname=0672319942&snode=257&now=6%2F1%2F2002+6%3A27%3A44+PM" TABINDEX="-1"><img src=images/spacer.gif border=0 width=1 height=1></a><br>
<FONT><h3>Python/C API</h3>
<p>The Application Programmer's Interface to Python gives C and C++ programmers access to the Python interpreter at a variety of levels. The API is equally usable from C++, but for brevity it is generally referred to as the Python/C API. There are two fundamentally different reasons for using the Python/C API. The first reason is to write extension modules for specific purposes; these are C modules that extend the Python interpreter. This is probably the most common use. The second reason is to use Python as a component in a larger application; this technique is generally referred to as embedding Python in an application.</p>
<P>Writing an extension module is a relatively well-understood process in which a "cookbook" approach works well. Several tools automate the process to some extent. Although people have embedded Python in other applications since its early existence, the process of embedding Python is less straightforward than writing an extension.</P>
<P>Many API functions are useful independent of whether you're embedding or extending Python; moreover, most applications that embed Python will need to provide a custom extension as well, so it's probably a good idea to become familiar with writing an extension before attempting to embed Python in a real application.</P>
<p>Python 1.5 introduces a number of new API functions as well as some changes to the build process that make embedding much simpler. This book describes the 1.5.2 state of affairs.</p>
<h4>Include Files</h4>
<P>All function, type, and macro definitions needed to use the Python/C API are included in your code by the following line:</P>
<PRe>
#include "Python.h"
</pre>
<P>This implies inclusion of the following standard headers: <TT Class="monofont"><stdio.h>,</tt>
<tt class="monofont"><string.h>,</tt>
<tt claSs="monofont"><errno.h>,</tT> and <tt cLass="monofont"><stdlib.h></tT> (if available).</p>
<p>All user visible names defined by Python.h (except those defined by the included standard headers) have one of the prefixes <tT CLAss="monofont">Py</tt> or <TT CLass="monofont">_Py.</tT> Names beginning with <TT Class="monofont">_Py</TT> are for internal use by the Python implementation and should not be used by extension writers. Structure member names do not have a reserved prefix.</P>
<P>Important: User code should never define names that begin with <tt class="monofont">Py</tt> or <tt class="monofont">_Py.</tt> This confuses the reader and jeopardizes the portability of the user code to future Python versions, which might define additional names beginning with one of these prefixes.<a nAme="idx1073750764"></A><a naMe="idx1073750765"></a><a nAme="idx1073750766"></a></P>
<P>The <A Name="idx1073750767"></a><A NAMe="idx1073750768"></a>header files are typically installed with Python. On UNIX, these are located in the directories <tt CLASs="monofont">$prefix/include/pythonversion/</tt> and <tT CLAss="monofont">$exec_prefix/include/ pythonversion/,</tt> where <tt class="monofont">$prefix</tt> and <tt class="monofont">$exec_prefix</Tt> are defined by the corresponding parameters to Python's configure script and the version is <tT claSs="monofont">sys.version[:3].</tt> On Windows, the headers are installed in <tT claSS="monofont">$prefix/include,</TT> where <tt clASS="monofont">$prefix</Tt> is the installation directory specified to the installer.</p>
<p>To include the headers, place both directories (if different) on your compiler's search path for includes. Do not place the parent directories on the search path and then use <tT CLAss="monofont">#include <python1.5/Python.h></tt>; this will break on multi-platform builds because the platform independent headers under <TT CLass="monofont">$prefix</tt> include the platform specific headers from <tt class="monofont">$exec_prefix.</tt></p>
<h4>Objects, Types, and Reference Counts</h4>
<p>Most Python/C API functions have one or more arguments as well as a return value of type <tt ClaSs="monofont">PyObject*.</tt> This type is a pointer to an opaque data type representing an arbitrary Python object. Because all Python object types are treated the same way by the Python language in most situations (for example, assignments, scope rules, and argument passing), it is only fitting that they should be represented by a single C type. Almost all Python objects live on the heap: You never declare an automatic or static variable of type PyObject; only pointer variables of type <Tt claSs="monofont">PyObject*</tt> can be declared. The sole exceptions are the type objects; because these must never be deallocated, they are typically static <TT CLass="monofont">PyTypeObject</tT> objects.</P>
<P>All Python objects (even Python integers) have a type and a reference count. An object's type determines what kind of object it is (for example, an integer, a list, or a user-defined function; there are many more as explained in the Python Reference Manual). For each of the well-known types, there is a macro to check whether an object is of that type; for instance, <Tt claSS="monofont">PyList_Check(a)</TT> is true if (and only if) the object it points to is a Python list.<a namE="idx1073750769"></A><A Name="idx1073750770"></a><a name="idx1073750771"></a><a name="idx1073750772"></a><a namE="idx1073750773"></a><a Name="idx1073750774"></A></p>
<h5>Reference Counts</h5>
<p>The reference count is important because today's computers have a finite (and often severely limited) memory size; it counts how many different places there are that have a reference to an object. Such a place could be another object, a global (or static) C variable, or a local variable in some C function. When an object's reference count becomes zero, the object is deallocated. If it contains references to other objects, their reference count is decremented. Those other objects might be deallocated in turn, if this decrement makes their reference count become zero, and so on. (There's an obvious problem with objects that reference each other here; for now, the solution is don't do that.)</P>
<p>Reference counts are always manipulated explicitly. The normal way is to use the <a nAME="idx1073750775"></A>macro <a namE="idx1073750776"></A><A Name="idx1073750777"></a><TT CLass="monofont">Py_INCREF()</tT> to increment an object's reference count by one, and <A NAme="idx1073750778"></a><a name="idx1073750779"></a><tt class="monofont">Py_DECREF()</tt> to decrement it by one. The decref macro is considerably more complex than the incref one because it must check whether the reference count becomes zero, and then causes the object's deallocation by calling a function contained in the object's type structure. The type-specific deallocator takes care of <a nAme="idx1073750780"></A>decrementing the reference counts for other objects contained in the object, and so on, if this is a compound object type such as a list. There's no chance that the reference count can overflow; at least as many bits are used to hold the reference count as there are distinct memory locations in virtual memory (assuming <tt cLass="monofont">sizeof(long) >= sizeof(char *)</tT>). Thus, the reference count increment is a simple operation. You should only pass a variable to <tt cLASS="monofont">Py_DECREF</tt> or <a nAME="idx1073750781"></A><a namE="idx1073750782"></A><TT clasS="monofont">Py_XDECREF.</TT> If you pass an expression, it will be evaluated multiple times (so don't use <Tt class="monofont">Py_XDECREF(func(...))</tt> to ignore the return value of a function).<a name="idx1073750783"></a><a name="idx1073750784"></a><A naMe="idx1073750785"></a><a Name="idx1073750786"></a><A namE="idx1073750787"></A><A Name="idx1073750788"></a><A NAMe="idx1073750789"></a></p>
<p>It is not necessary to <A NAMe="idx1073750790"></a>increment an object's reference count for every local variable that contains a pointer to an object. In theory, the object's reference count goes up by one when the variable is made to point to it, and it goes down by one when the variable goes out of scope. However, these two cancel each other out, so at the end, the reference count hasn't changed. The only real reason to use the reference count is to prevent the object from being deallocated as long as our variable is pointing to it. If we know that there is at least one other reference to the object that lives at least as long as our variable, there is no need to increment the reference count temporarily. An important situation in which this arises is in objects that are passed as arguments to C functions in an extension module that are called from Python; the call mechanism guarantees to hold a reference to every argument for the duration of the call.</p>
<p>However, a common pitfall is to extract an object from a list and hold on to it for a while without incrementing its reference count. Some other operation might conceivably remove the object from the list, decrementing its reference count, and possibly deallocating it. The real danger is that innocent-looking operations might invoke arbitrary Python code that could do this; there is a code path that allows control to flow back to the user from a <TT CLass="monofont">Py_DECREF(),</tt> so almost any operation is potentially dangerous.</p>
<p>A safe approach is to always use the generic operations (functions whose name begins with <tt class="monofont">PyObject_,</tt>
<tt clAss="monofont">PyNumber_,</Tt>
<tt Class="monofont">PySequence_,</Tt> or <tt CLASs="monofont">PyMapping_</tt>). These operations always increment the reference count of the object they return. This leaves the caller with the responsibility to call <tT CLAss="monofont">Py_DECREF()</tt> when they are done with the result; this soon becomes second nature.<A NAMe="idx1073750791"></a><a nAME="idx1073750792"></A><a name="idx1073750793"></a><a name="idx1073750794"></a></p>
<h5>Reference Count Details</h5>
<p>The reference count behavior of <a namE="idx1073750795"></a>functions in the Python/C API is best explained in terms of ownership of references. Note that we talk of owning references, never of owning objects; objects are always shared. When a function owns a reference, it has to dispose of it properly梕ither by passing ownership on (usually to its caller) or by calling <tT claSs="monofont">Py_DECREF()</tt> or <a Name="idx1073750796"></A><A NAme="idx1073750797"></a><tT CLAss="monofont">Py_XDECREF().</tt> When a function passes ownership of a reference on to its caller, the caller is said to receive a new reference. When no ownership is transferred, the caller is said to <A NAMe="idx1073750798"></a>borrow the reference. Nothing needs to be done for a borrowed reference.<a nAME="idx1073750799"></A><a name="idx1073750800"></a><a name="idx1073750801"></a><a name="idx1073750802"></a><a nAme="idx1073750803"></A><a naMe="idx1073750804"></a><a nAme="idx1073750805"></a><A NAMe="idx1073750806"></a><a nAME="idx1073750807"></A></p>
<p>Conversely, when calling a function passes it a reference to an object, there are two possibilities: The function <a nAME="idx1073750808"></A>steals a reference to the object, or it does not. Few functions steal references; the two notable exceptions are <a namE="idx1073750809"></A><A Name="idx1073750810"></a><tt class="monofont">PyList_SetItem()</tt> and <a name="idx1073750811"></a><a NamE="idx1073750812"></a><tt Class="monofont">PyTuple_SetItem(),</Tt> which steal a reference to the item (but not to the tuple or list into which the item is put). These functions were designed to steal a reference because of a common idiom for populating a tuple or list with newly created objects; for example, the code to create the tuple (1, 2, "three") could look similar to this (forget about error handling for the moment):</p>
<pRE>
PyObject *t;
t = PyTuple_New(3);
PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
PyTuple_SetItem(t, 2, PyString_FromString("three"));
</PRe>
<p>Incidentally, <tt CLASs="monofont">PyTuple_SetItem()</tt> is the only way to <a NAME="idx1073750813"></a><a naME="idx1073750814"></A><A name="idx1073750815"></a>set tuple items; <tt class="monofont">PySequence_SetItem()</tt> and <tt clasS="monofont">PyObject_SetItem()</tt> refuse to do this because tuples are an immutable data type. You should only use <Tt clAss="monofont">PyTuple_SetItem()</tt> for tuples that you are creating yourself.</P>
<p>Equivalent code for <a nAME="idx1073750816"></A><a namE="idx1073750817"></A>populating a list can be written using <A Name="idx1073750818"></a><A NAMe="idx1073750819"></a><tt CLASs="monofont">PyList_New()</tt> and <tt class="monofont">PyList_SetItem().</tt> Such code can also use <a name="idx1073750820"></a><a nAme="idx1073750821"></A><tt cLass="monofont">PySequence_SetItem()</tT>; this illustrates the difference between the two (the extra <tt cLASS="monofont">Py_DECREF()</tt> calls):</p>
<pRE>
PyObject *l, *x;
l = PyList_New(3);
x = PyInt_FromLong(1L);
PySequence_SetItem(l, 0, x); Py_DECREF(x);
x = PyInt_FromLong(2L);
PySequence_SetItem(l, 1, x); Py_DECREF(x);
x = PyString_FromString("three");
PySequence_SetItem(l, 2, x); Py_DECREF(x);
</PRe>
<p>You might find it strange that the recommended approach takes more code. However, in practice, you will rarely use these ways of creating and populating a tuple or list. There's a generic function, <a nAME="idx1073750822"></A><a namE="idx1073750823"></A><TT class="monofont">Py_BuildValue(),</tt> that can create most common objects from C values, directed by a format string. For example, the previous two blocks of code could be replaced by the following (which also takes care of the <a name="idx1073750824"></a><a name="idx1073750825"></a>error checking):</p>
<Pre>
PyObject *t, *l;
t = Py_BuildValue("(iis)", 1, 2, "three");
l = Py_BuildValue("[iis]", 1, 2, "three");
</Pre>
<p>It is more common to use <A name="idx1073750826"></A><a naME="idx1073750827"></A><Tt claSS="monofont">PyObject_SetItem()</TT> and become friends with items whose references you are only borrowing, like arguments that were passed in to the function you are writing. In that case, their behavior regarding reference counts is much saner because you don't have to increment a reference count so you can give a reference away (have it be stolen). For example, this function <a namE="idx1073750828"></A><A Name="idx1073750829"></a><A NAMe="idx1073750830"></a>sets all items of a list (actually, any mutable sequence) to a given item:</p>
<pre>
int set_all(PyObject *target, PyObject *item)
{
int i, n;
n = PyObject_Length(target);
if (n < 0)
return -1;
for (i = 0; i < n; i++) {
if (PyObject_SetItem(target, i, item) < 0)
return -1;
}
return 0;
}
</pre>
<p>The situation is slightly different for function return values. Although <a name="idx1073750831"></a><a namE="idx1073750832"></a>passing a reference to most functions does not change your ownership responsibilities for that reference, many functions that return a reference to an object give you <a Name="idx1073750833"></A>ownership of the reference. The reason is simple: In many cases, the returned object is created on-the-fly, and the reference you get is the only reference to the object. Therefore, the generic functions that return object references, such as <a namE="idx1073750834"></a><a nAME="idx1073750835"></A><tt clASS="monofont">PyObject_GetItem()</Tt> and <a naME="idx1073750836"></A><A name="idx1073750837"></A><TT Class="monofont">PySequence_GetItem(),</tt> always return a new reference (that is, the caller becomes the owner of the reference).</p>
<p>It is important to realize that whether you own a reference returned by a function only depends on which function you call梩he plumage (that is, the type of the object passed as an argument to the function) doesn't enter into it. Thus, if you extract an item from a list using <tt class="monofont">PyList_GetItem(),</tt> you don't own the reference梑ut if you obtain the same item from the same list using <tt cLasS="monofont">PySequence_GetItem()</tt> (which happens to take exactly the same arguments), you do own a reference to the returned object.</p>
<P>Here is an example of how you could write a function that computes the sum of the items in a list of integers; once using <a namE="idx1073750838"></a><a nAME="idx1073750839"></A><tt clASS="monofont">PyList_GetItem(),</Tt> once using <tt cLASS="monofont">PySequence_GetItem()</tt>:<a nAME="idx1073750840"></A><a name="idx1073750841"></a><a name="idx1073750842"></a><a name="idx1073750843"></a><a nAme="idx1073750844"></A><a naMe="idx1073750845"></a><a nAme="idx1073750846"></a><A NAMe="idx1073750847"></a><a nAME="idx1073750848"></A><a namE="idx1073750849"></A><A Name="idx1073750850"></a><A NAMe="idx1073750851"></a><a name="idx1073750852"></a><a name="idx1073750853"></a><a name="idx1073750854"></a></P>
<prE>
long sum_list(PyObject *list)
{
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -