tags:

views:

105

answers:

2

I'm writing a Python wrapper for a C++ library, and I'm getting a really weird when trying to set a struct's field in C. If I have a struct like this:

struct Thing
{
    PyOBJECT_HEAD
    unsigned int val;
};

And have two functions like this:

static PyObject* Thing_GetBit(Thing* self, PyObject* args)
{
    unsigned int mask;

    if(!PyArg_ParseTuple(args, "I", &mask))
        Py_RETURN_FALSE;

   if((self->val & mask) != 0)
       Py_RETURN_TRUE;

    Py_RETURN_FALSE;
}


static PyObject* Thing_SetBit(Thing* self, PyObject* args)
{
    unsigned int mask;
    bool on;

    if(!PyArg_ParseTuple(args, "Ii", &mask, &on))
        Py_RETURN_FALSE;

    if(on)
        self->val |= mask;
    else
        self->val &= ~mask;

    Py_RETURN_TRUE;
}

Python code that calls the first method works just fine, giving back the value of the struct member. Calls to the SetBit method give an error about an object at address foo accessing memory at address bar, which couldn't be "written".

I've poked around the code, and it's like I can look at the value all I want, both from C and Python, but the instant I try to set it, it blows up in my face. Am I missing something fundamental here?

+1  A: 

Shouldn't it be:

if (on)
    self->val |= mask;
else
    self->val &= ~mask;
plinth
Gah. Yeah, I screwed up while typing it out.
Lee Crabtree
+2  A: 

Is it possible that passing the address of a bool PyArg_ParseTuple is causing your trouble? The "i" format will write an int sized thing.

What kind of machine are you running on?

Richard Pennington
It's a Core2 Duo laptop. Python bools are supposed to be integers on the inside, I thought.EDIT: Ye Gods. That was it. I switched to an int, and suddenly it doesn't explode. What the *hell*.
Lee Crabtree
@Lee: Python bools may be integers, but C++'s are not :-) (e.g. they're bytes for Visual C++)
RaphaelSP
Color me embarrassed.
Lee Crabtree