creating simple Python scripting interfaces via C++

Ben Sizer kylotan at gmail.com
Thu Jan 11 06:43:53 EST 2007


Ok, my first attempt at this creates proxy objects in Python, and
stores a pointer to the C++ instance in the Python object. I cast that
pointer to an int and pass it as a single parameter to the object's
__init__ function.

static PyObject* Actor_init(PyObject *self, PyObject *args)
{
    PyObject* selfParam;
    PyObject* ptrValue;
    if (!PyArg_ParseTuple(args, "OO", &selfParam, &ptrValue))
        return NULL;

    PyObject_SetAttrString(selfParam, "_cpp_ptr", ptrValue);

    Py_INCREF(Py_None);
    return Py_None;
}

I have no idea why self is always NULL, when I'm calling the functions
as methods of an object. Any ideas why this is the case? For what it's
worth I attach each method via the PyMethodDef -> PyCFunction_New ->
PyMethod_New -> PyDict_SetItemString(classDict) route.

To get data back from the C++ object to Python, I extract that value
and cast it back to the appropriate pointer type.

static PyObject* Actor_showName(PyObject *self, PyObject *args)
{
    PyObject* selfParam;
    if (!PyArg_ParseTuple(args, "O", &selfParam))
        return NULL;

    PyObject* cppPtr = PyObject_GetAttrString(selfParam, "_cpp_ptr");
    long cppPtrVal = PyInt_AsLong(cppPtr);
    Actor* pActor = reinterpret_cast<Actor*>(cppPtrVal);

    // Delegate to the C++ object
    pActor->ShowName();

    Py_INCREF(Py_None);
    return Py_None;
}

I've omitted some error checking, but this is the way I'm going for
now. Are there any glaring errors I've made (apart from perhaps
assuming sizeof(pointer) <= sizeof(long), that is)? And is there
anywhere else more appropriate that I should be asking this question,
given the lack of responses to this and my other embedding topic so
far?

-- 
Ben Sizer




More information about the Python-list mailing list