Suggestion for easier c/c++ interfacing

Michael P. Reilly arcege at shore.net
Fri Apr 23 12:34:46 EDT 1999


Albert Hofkamp <hat at se-46.wpa.wtb.tue.nl> wrote:
: Hello all,

: I have been experimenting with c++ and Python, and am working on
: attaching generated c++ module-code to python.

: In the EXT document, it is explained how to parse arguments from python
: in c code using PyTuple_ParseArgs(). This is really easy to use.

I think you mean PyArg_ParseTuple().

: However, the same kind of parsing must occur after a call from c to a
: python function. The return value from that function is again a Python
: object, and needs to be decoded before it can be used in c.
: Unfortunately, the returned value is not a tuple, so PyTuple_ParseArgs()
: cannot be used. A shortcut would be to wrap the result in a tuple with 1
: argument, and then call the decoding function, but I consider that a hack.

: Wouldn't it be possible to create a PyTuple_ParseArgs()-like function to
: parse return results from python functions ?

Gee... that is what happens when you take something out of the doc.

There is indeed a function that you describe.  It is not used often,
but "in the old days" it was used instead of PyArg_ParseTuple().  The
function is called PyArg_Parse() and works identically to the function
PyArg_ParseTuple(), except that it does not expect a tuple, it expects
any Python object.

  PyObject *function;
  PyObject *result, *args;
  char *street, *town, *city;
  int zipcode;

  args = Py_BuildValue("ss", "name", "Arcege");
  /* returns a list of four elements */
  result = PyObject_CallObject(function, args);
  Py_DECREF(args);
  if (!PyArg_Parse(result, "[sssi]", &street, &town, &city, &zipcode))
      return NULL;

Often, it is better to determine the type of the return value in the C
code manually - making it more robust and extensible.

  result = PyObject_CallObject(function, args);
  if (result == Py_None) {
      printf("No address found\n");
      Py_DECREF(Py_None);
  } else if (!PyList_Check(result)) {
      PyErr_SetString(PyExc_TypeError, "expecting a list (or None)")
      return NULL;
  }

A good idea is to go thru the Python sources and see how PyArg_Parse
is still being used.

  -Arcege





More information about the Python-list mailing list