質問

どのように私は、PythonのC APIを使用して、次のPythonの関数をシミュレートすることができますか?

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