[C++-SIG] Python calling C++ issues

Duncan Grisby dgrisby at uk.research.att.com
Wed Dec 1 14:55:44 CET 1999

On Wednesday 1 December, "Adrian Eyre" wrote:


> 'Spam' is a C++ object, not a python object, and you can't just cast it
> to a PyObject* and expect it to work. One way to do this is to pass back
> a pointer to the object as a long:
> static PyObject*
> ext_new_Spam(PyObject* self, PyObject* args)
> {
> 	int a, b;
> 	if (!PyArg_ParseTuple(args, "ii", &a, &b))
> 		return NULL;
> 	Spam* spam = new Spam(a, b);
> 	return Py_BuildValue("l", (long) spam); // Or return PyInt_FromLong((long)

I haven't particularly followed the discussion, but I just want to
point out that doing what you suggest is extremely dangerous. There is
no guarantee that longs are the same size as pointers. There is also
nothing to stop the Python code from modifying the integer, causing
the C code to dereference arbitrary memory locations. It shouldn't be
possible for Python code to cause core dumps. You should use
PyCObjects instead.



 -- Duncan Grisby  \  Research Engineer  --
  -- AT&T Laboratories Cambridge          --
   -- http://www.uk.research.att.com/~dpg1 --

More information about the Cplusplus-sig mailing list