문제

Python C API를 사용하여 다음 파이썬 기능을 어떻게 시뮬레이션 할 수 있습니까?

def foo(bar, baz="something or other"):
    print bar, baz

(즉, 다음을 통해 호출 할 수 있도록 :

>>> foo("hello")
hello something or other
>>> foo("hello", baz="world!")
hello world!
>>> foo("hello", "world!")
hello, world!

)

도움이 되었습니까?

해결책

보다 문서: 당신은 사용하고 싶습니다 PyArg_ParseTupleAndKeywords, 내가 준 URL에 문서화.

예를 들어 :

def foo(bar, baz="something or other"):
    print bar, baz

(대략 - 테스트하지 않았다!) : : :

#include "Python.h"

static PyObject *
themodule_foo(PyObject *self, PyObject *args, PyObject *keywds)
{
    char *bar;
    char *baz = "something or other";

    static char *kwlist[] = {"bar", "baz", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, keywds, "s|s", kwlist,
                                     &bar, &baz))
        return NULL;

    printf("%s %s\n", bar, baz);

    Py_INCREF(Py_None);
    return Py_None;
}

static PyMethodDef themodule_methods[] = {
    {"foo", (PyCFunction)themodule_foo, METH_VARARGS | METH_KEYWORDS,
     "Print some greeting to standard output."},
    {NULL, NULL, 0, NULL}   /* sentinel */
};

void
initthemodule(void)
{
  Py_InitModule("themodule", themodule_methods);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top