سؤال

كيف يمكنني محاكاة وظيفة بيثون التالية باستخدام API Python C؟

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