C API: passing by reference

stuart.tett at gmail.com stuart.tett at gmail.com
Sat Jun 23 20:56:14 CEST 2007

Thanks for that clarification Martin. When I googled it before, the
first page I read said "Python passes all arguments using 'pass by
reference'." However, after seeing your reply and further searching I
see that this is not true.

I have a python function insertEdge which takes to 2-tuples of
(faceid,vertexid) and returns the edgeid. But upon execution of the
function the two vertexid's end up sharing the same faceid. So right
now my solution is just to also return the two new (faceid,vertexid).
These will both have the same vertexid as before, but have a different
faceid then before (sharing the same faceid).

Here for example is a script to create a triangle:

  v1 = createVertex((0,0,0))
  v2 = createVertex((1,0,0))
  e1,v1,v2 = insertEdge(v1,v2)
  v3 = createVertex((0,1,0))
  e2,v2,v3 = insertEdge(v2,v3)
  e3,v3,v1 = insertEdge(v3,v1)

Here is the C++ code:

static PyObject *
dlfl_insert_edge(PyObject *self, PyObject *args)
  uint faceId1;
  int vertId1;
  uint faceId2;
  int vertId2;
  int edgeId = -1;

  if( !PyArg_ParseTuple(args, "(ii)(ii)", &faceId1, &vertId1,
&faceId2, &vertId2) )
    return NULL;

  if( currObj ) {
    edgeId = DLFL::insertEdge( currObj, faceId1, vertId1, faceId2,
vertId2 );
    currObj->clearSelected( );

  return Py_BuildValue("i,(ii)(ii)", edgeId, faceId1, vertId1,
faceId2, vertId2 );

This works, but...
Any suggestions if there is a cleaner way?


On Jun 23, 1:31 pm, "Martin v. Löwis" <mar... at v.loewis.de> wrote:
> stuart.t... at gmail.com schrieb:
> > I'm writing my own python extension module with the C API. In python
> > all functions pass arguments by reference
> Can you please show an example what you mean by that? There is no
> "pass-by-reference" in Python: a function can not normally modify
> the variable in the caller.
> When you show what precisely you want to achieve, it should be easy
> to say how to do that in C.
> Regards,
> Martin

More information about the Python-list mailing list