Passing Named Paramater To A C Func?

Fredrik Lundh fredrik at pythonware.com
Tue Apr 29 07:04:14 EDT 2003


John Abel wrote:

> I'm writing a C function, which will have a Python wrapper, and I wish
> to be able to pass it an optional, named parameter.  For example:
>
> def funcName( dirName, fileName=None ):
>
>    if fileName is None:
>        Some Other Stuff
>
>    cCall( dirName, fileName )
>
> Is the best to handle this in the Python wrapper, or is there a way of
> handling these via C.  None of the extending documents seem to mention
> anything about this.

to handle named arguments on the C level, use ParseTupleAndKeywords.
here's an example, taken from the regular expression engine:

static PyObject*
pattern_match(PatternObject* self, PyObject* args, PyObject* kw)
{
    ...

    PyObject* string;
    int start = 0;
    int end = INT_MAX;
    static char* kwlist[] = { "pattern", "pos", "endpos", NULL };
    if (!PyArg_ParseTupleAndKeywords(args, kw, "O|ii:match", kwlist,
                                     &string, &start, &end))
        return NULL;

you also have to set the METH_KEYWORDS flag in the PyMethodDef
table:

static PyMethodDef pattern_methods[] = {
    {"match", (PyCFunction) pattern_match, METH_VARARGS|METH_KEYWORDS},
    ...

:::

in your case, I'm not sure it's really worth the effort, since you
need to look at the argument at the Python level anyway.

</F>








More information about the Python-list mailing list