C API with *args and **kw

Miki miki.tebeka at gmail.com
Tue Oct 14 14:07:12 EDT 2008


Hello All,

I'm try to write the C equivalent of:

def kw(*args, **kw):
    print "%d args" % len(args),
    if "default" in kw:
        print "default is %s" % kw["default"]
    else:
        print "no default"

I've written:
static PyObject *
kw(PyObject *self, PyObject *args, PyObject *kwds) {
    PyObject *defval = NULL;
    long nargs;
    char *str;

    nargs = PyTuple_GET_SIZE(args);
    printf("%d args ", nargs);

    defval = PyDict_GetItemString(kwds, "default");

    if (NULL == defval) {
        printf("no default\n");
    }
    else {
        str = PyString_AsString(defval);
        printf("default is %s\n", str);
    }

    return Py_BuildValue("");
}

However when running the test:
from kw import kw
kw(default="2")
kw(1)
kw()

I get "bus error" on the 2'nd call (OS X Python 2.5.2).

Any idea?

TIA,
--
Miki <miki.tebeka at gmail.com>
http://pythonwise.blogspot.com



More information about the Python-list mailing list