Why does setting this member in C fail?
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 PyObje开发者_开发知识库ct* 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?
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?
Shouldn't it be:
if (on)
self->val |= mask;
else
self->val &= ~mask;
精彩评论