Question: handling buffers of data in C extensions

Russell E. Owen owen at astrono.junkwashington.emu
Wed Jul 25 11:46:36 EDT 2001

In a C extension module, I am trying to implement a read function 
(something that passes back a buffer of data that Python should own and 
dispose of when it's ready to). I'm a bit confused about the best way to 
go about this.

I've appended what I have so far. I suspect it *might* work, but that 
there is a better way. My main concern is that PyString_AsString returns 
a null-terminated string, which is inappropriate and perhaps wrong; if 
the PyString is expecting the final buffer to be null-terminated I'm in 

The documentation mentions buffer functions that sound much more 
appropriate, but I've not been able to figure out how they work. Any 
advice would be appreciated.

-- Russell

static PyObject *read (PyObject *self, PyObject *args)
    PyObject *py_edt_p;
    EdtDev *edt_p;
    int size;
    PyObject *py_buf_p;
    /* parse arguments */
    if (!PyArg_ParseTuple(args, "Ni", &py_edt_p, &size){
        return NULL;
    edt_p = (EdtDev *) PyLong_AsVoidPtr(py_edt_p);
    if (edt_p == NULL{
        return NULL;
    /* create a new Python string of the appropriate size
    and get a pointer to its internal buffer */
    py_buf_p = PyString_FromStringAndSize(NULL, size);
    buf_p = PyString_AsString(py_buf_p);
    /* fill the internal buffer and return the string */    
    if (0 != edt_read((EdtDev *) edt_p, buf_p, size){
        PyErr_SetString(PyExc_RuntimeError, edt_errStr);
        return NULL;
    return py_buf_p;

More information about the Python-list mailing list