Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / src / nas,5.n2.os.2 / lib / python / html / python / ext / callingPython.html
CommitLineData
86530b38
AT
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<html>
3<head>
4<link rel="STYLESHEET" href="ext.css" type='text/css' />
5<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
6<link rel='start' href='../index.html' title='Python Documentation Index' />
7<link rel="first" href="ext.html" title='Extending and Embedding the Python Interpreter' />
8<link rel='contents' href='contents.html' title="Contents" />
9<link rel='last' href='about.html' title='About this document...' />
10<link rel='help' href='about.html' title='About this document...' />
11<link rel="next" href="parseTuple.html" />
12<link rel="prev" href="compilation.html" />
13<link rel="parent" href="intro.html" />
14<link rel="next" href="parseTuple.html" />
15<meta name='aesop' content='information' />
16<title>1.6 Calling Python Functions from C
17</title>
18</head>
19<body>
20<DIV CLASS="navigation">
21<div id='top-navigation-panel' xml:id='top-navigation-panel'>
22<table align="center" width="100%" cellpadding="0" cellspacing="2">
23<tr>
24<td class='online-navigation'><a rel="prev" title="1.5 Compilation and Linkage"
25 href="compilation.html"><img src='../icons/previous.png'
26 border='0' height='32' alt='Previous Page' width='32' /></A></td>
27<td class='online-navigation'><a rel="parent" title="1. Extending Python with"
28 href="intro.html"><img src='../icons/up.png'
29 border='0' height='32' alt='Up One Level' width='32' /></A></td>
30<td class='online-navigation'><a rel="next" title="1.7 Extracting Parameters in"
31 href="parseTuple.html"><img src='../icons/next.png'
32 border='0' height='32' alt='Next Page' width='32' /></A></td>
33<td align="center" width="100%">Extending and Embedding the Python Interpreter</td>
34<td class='online-navigation'><a rel="contents" title="Table of Contents"
35 href="contents.html"><img src='../icons/contents.png'
36 border='0' height='32' alt='Contents' width='32' /></A></td>
37<td class='online-navigation'><img src='../icons/blank.png'
38 border='0' height='32' alt='' width='32' /></td>
39<td class='online-navigation'><img src='../icons/blank.png'
40 border='0' height='32' alt='' width='32' /></td>
41</tr></table>
42<div class='online-navigation'>
43<b class="navlabel">Previous:</b>
44<a class="sectref" rel="prev" href="compilation.html">1.5 Compilation and Linkage</A>
45<b class="navlabel">Up:</b>
46<a class="sectref" rel="parent" href="intro.html">1. Extending Python with</A>
47<b class="navlabel">Next:</b>
48<a class="sectref" rel="next" href="parseTuple.html">1.7 Extracting Parameters in</A>
49</div>
50<hr /></div>
51</DIV>
52<!--End of Navigation Panel-->
53
54<H1><A NAME="SECTION003600000000000000000"></A><A NAME="callingPython"></A>
55<BR>
561.6 Calling Python Functions from C
57
58</H1>
59
60<P>
61So far we have concentrated on making C functions callable from
62Python. The reverse is also useful: calling Python functions from C.
63This is especially the case for libraries that support so-called
64``callback'' functions. If a C interface makes use of callbacks, the
65equivalent Python often needs to provide a callback mechanism to the
66Python programmer; the implementation will require calling the Python
67callback functions from a C callback. Other uses are also imaginable.
68
69<P>
70Fortunately, the Python interpreter is easily called recursively, and
71there is a standard interface to call a Python function. (I won't
72dwell on how to call the Python parser with a particular string as
73input -- if you're interested, have a look at the implementation of
74the <b class="programopt">-c</b> command line option in <span class="file">Python/pythonmain.c</span>
75from the Python source code.)
76
77<P>
78Calling a Python function is easy. First, the Python program must
79somehow pass you the Python function object. You should provide a
80function (or some other interface) to do this. When this function is
81called, save a pointer to the Python function object (be careful to
82<tt class="cfunction">Py_INCREF()</tt> it!) in a global variable -- or wherever you
83see fit. For example, the following function might be part of a module
84definition:
85
86<P>
87<div class="verbatim"><pre>
88static PyObject *my_callback = NULL;
89
90static PyObject *
91my_set_callback(PyObject *dummy, PyObject *args)
92{
93 PyObject *result = NULL;
94 PyObject *temp;
95
96 if (PyArg_ParseTuple(args, "O:set_callback", &amp;temp)) {
97 if (!PyCallable_Check(temp)) {
98 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
99 return NULL;
100 }
101 Py_XINCREF(temp); /* Add a reference to new callback */
102 Py_XDECREF(my_callback); /* Dispose of previous callback */
103 my_callback = temp; /* Remember new callback */
104 /* Boilerplate to return "None" */
105 Py_INCREF(Py_None);
106 result = Py_None;
107 }
108 return result;
109}
110</pre></div>
111
112<P>
113This function must be registered with the interpreter using the
114<tt class="constant">METH_VARARGS</tt> flag; this is described in section
115<A href="methodTable.html#methodTable">1.4</A>, ``The Module's Method Table and Initialization
116Function.'' The <tt class="cfunction">PyArg_ParseTuple()</tt> function and its
117arguments are documented in section&nbsp;<A href="parseTuple.html#parseTuple">1.7</A>, ``Extracting
118Parameters in Extension Functions.''
119
120<P>
121The macros <tt class="cfunction">Py_XINCREF()</tt> and <tt class="cfunction">Py_XDECREF()</tt>
122increment/decrement the reference count of an object and are safe in
123the presence of <tt class="constant">NULL</tt> pointers (but note that <var>temp</var> will not be
124<tt class="constant">NULL</tt> in this context). More info on them in
125section&nbsp;<A href="refcounts.html#refcounts">1.10</A>, ``Reference Counts.''
126
127<P>
128Later, when it is time to call the function, you call the C function
129<tt class="cfunction">PyEval_CallObject()</tt>.<a id='l2h-1' xml:id='l2h-1'></a> This
130function has two arguments, both pointers to arbitrary Python objects:
131the Python function, and the argument list. The argument list must
132always be a tuple object, whose length is the number of arguments. To
133call the Python function with no arguments, pass an empty tuple; to
134call it with one argument, pass a singleton tuple.
135<tt class="cfunction">Py_BuildValue()</tt> returns a tuple when its format string
136consists of zero or more format codes between parentheses. For
137example:
138
139<P>
140<div class="verbatim"><pre>
141 int arg;
142 PyObject *arglist;
143 PyObject *result;
144 ...
145 arg = 123;
146 ...
147 /* Time to call the callback */
148 arglist = Py_BuildValue("(i)", arg);
149 result = PyEval_CallObject(my_callback, arglist);
150 Py_DECREF(arglist);
151</pre></div>
152
153<P>
154<tt class="cfunction">PyEval_CallObject()</tt> returns a Python object pointer: this is
155the return value of the Python function. <tt class="cfunction">PyEval_CallObject()</tt> is
156``reference-count-neutral'' with respect to its arguments. In the
157example a new tuple was created to serve as the argument list, which
158is <tt class="cfunction">Py_DECREF()</tt>-ed immediately after the call.
159
160<P>
161The return value of <tt class="cfunction">PyEval_CallObject()</tt> is ``new'': either it
162is a brand new object, or it is an existing object whose reference
163count has been incremented. So, unless you want to save it in a
164global variable, you should somehow <tt class="cfunction">Py_DECREF()</tt> the result,
165even (especially!) if you are not interested in its value.
166
167<P>
168Before you do this, however, it is important to check that the return
169value isn't <tt class="constant">NULL</tt>. If it is, the Python function terminated by
170raising an exception. If the C code that called
171<tt class="cfunction">PyEval_CallObject()</tt> is called from Python, it should now
172return an error indication to its Python caller, so the interpreter
173can print a stack trace, or the calling Python code can handle the
174exception. If this is not possible or desirable, the exception should
175be cleared by calling <tt class="cfunction">PyErr_Clear()</tt>. For example:
176
177<P>
178<div class="verbatim"><pre>
179 if (result == NULL)
180 return NULL; /* Pass error back */
181 ...use result...
182 Py_DECREF(result);
183</pre></div>
184
185<P>
186Depending on the desired interface to the Python callback function,
187you may also have to provide an argument list to
188<tt class="cfunction">PyEval_CallObject()</tt>. In some cases the argument list is
189also provided by the Python program, through the same interface that
190specified the callback function. It can then be saved and used in the
191same manner as the function object. In other cases, you may have to
192construct a new tuple to pass as the argument list. The simplest way
193to do this is to call <tt class="cfunction">Py_BuildValue()</tt>. For example, if
194you want to pass an integral event code, you might use the following
195code:
196
197<P>
198<div class="verbatim"><pre>
199 PyObject *arglist;
200 ...
201 arglist = Py_BuildValue("(l)", eventcode);
202 result = PyEval_CallObject(my_callback, arglist);
203 Py_DECREF(arglist);
204 if (result == NULL)
205 return NULL; /* Pass error back */
206 /* Here maybe use the result */
207 Py_DECREF(result);
208</pre></div>
209
210<P>
211Note the placement of "<tt class="samp">Py_DECREF(arglist)</tt>" immediately after the
212call, before the error check! Also note that strictly spoken this
213code is not complete: <tt class="cfunction">Py_BuildValue()</tt> may run out of
214memory, and this should be checked.
215
216<P>
217
218<DIV CLASS="navigation">
219<div class='online-navigation'>
220<p></p><hr />
221<table align="center" width="100%" cellpadding="0" cellspacing="2">
222<tr>
223<td class='online-navigation'><a rel="prev" title="1.5 Compilation and Linkage"
224 href="compilation.html"><img src='../icons/previous.png'
225 border='0' height='32' alt='Previous Page' width='32' /></A></td>
226<td class='online-navigation'><a rel="parent" title="1. Extending Python with"
227 href="intro.html"><img src='../icons/up.png'
228 border='0' height='32' alt='Up One Level' width='32' /></A></td>
229<td class='online-navigation'><a rel="next" title="1.7 Extracting Parameters in"
230 href="parseTuple.html"><img src='../icons/next.png'
231 border='0' height='32' alt='Next Page' width='32' /></A></td>
232<td align="center" width="100%">Extending and Embedding the Python Interpreter</td>
233<td class='online-navigation'><a rel="contents" title="Table of Contents"
234 href="contents.html"><img src='../icons/contents.png'
235 border='0' height='32' alt='Contents' width='32' /></A></td>
236<td class='online-navigation'><img src='../icons/blank.png'
237 border='0' height='32' alt='' width='32' /></td>
238<td class='online-navigation'><img src='../icons/blank.png'
239 border='0' height='32' alt='' width='32' /></td>
240</tr></table>
241<div class='online-navigation'>
242<b class="navlabel">Previous:</b>
243<a class="sectref" rel="prev" href="compilation.html">1.5 Compilation and Linkage</A>
244<b class="navlabel">Up:</b>
245<a class="sectref" rel="parent" href="intro.html">1. Extending Python with</A>
246<b class="navlabel">Next:</b>
247<a class="sectref" rel="next" href="parseTuple.html">1.7 Extracting Parameters in</A>
248</div>
249</div>
250<hr />
251<span class="release-info">Release 2.4.2, documentation updated on 28 September 2005.</span>
252</DIV>
253<!--End of Navigation Panel-->
254<ADDRESS>
255See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
256</ADDRESS>
257</BODY>
258</HTML>