Retain reference to a struct

andychambers2002 at yahoo.co.uk andychambers2002 at yahoo.co.uk
Wed Nov 2 16:23:52 EST 2005


Hi All,

A C library I'm using has a number of functions that all require a
struct as an argument.  The example module shows how to make a new
Python Object from C code and I've seen other posts that recommend this
way of doing it.

In this case though, it would seem easier if I could create the object
in the Python code.  This would require storing a pointer to an
instance of the struct until a certain function is called.

I can get the pointer into the python code, but whenever I try to use
it to call another function, the module segfaults.  Can anyone suggest
why this is?

static PyObject *
libpyq_PQconnectdb(PyObject *self, PyObject *args)
{
        PGconn *conn = PyMem_New(PGconn, sizeof(PGconn *));
        conn = (PGconn *)PQconnectdb((const char*)
PyString_AS_STRING(args));

        printf("%p", conn);
        return PyLong_FromVoidPtr(conn) ;
}

static PyObject *
libpyq_PQfinish(PyObject *self, PyObject *args)
{
        printf("%p", args);
        return 1;
}

>>> import libpyq                #works fine
>>> conn = libpyq.PQconnectdb    #conn now a pointer
>>> libpyq.PQfinish(conn)        #segfaults

I'm new to C but relatively experienced with Python.  I have a sneaky
suspiscion there's a good reason for not doing it this way but I
haven't seen a good explanation of why not yet.  If you know one,
please tell me.

Thanks,
Andy




More information about the Python-list mailing list