【问题标题】:How to declare a python c-extension method as a classmethod?如何将python c-extension方法声明为classmethod?
【发布时间】:2013-11-12 20:57:07
【问题描述】:

我正在为一个 C++ 类编写一个 python 包装器,它为备用“构造器”提供了几个静态方法。我想知道如何通过 python c-api 导出这些?

这是相关 C++ 代码的存根。

 PyObject *PyFoo_FromFoo(Foo foo);

 // This should be a class method that create a new instance of PyFoo().
 PyObject *
 PyFoo_Gen1(PyObject *self, PyObject *args)
 {
     Foo foo;  // Init this according to args

     return PyFoo_FromFoo(foo);
 }

 static PyMethodDef PyFoo_methods[] = {
    {"Gen1", (PyCFunction)PyFoo_Gen1, METH_VARARGS, "Gen1 foo creator" },
    {NULL}  /* Sentinel */
 };

 PyTypeObject PyFooType = {
   :
   PyFoo_methods, /* tp_methods */
   :
 }

 PyObject *PyFoo_FromFoo(Foo foo)
 {
    PyFoo *v = (PyFoo*)PyObject_New(PyFoo, &PyFooType);
    v->foo = foo;
    return (PyObject*)v;
 }

在上面的示例中为Gen1() 使用classmethod() 函数(直接或通过@classmethod 装饰器)对应的是什么?

【问题讨论】:

  • 我推荐使用 Cython 将 C/C++ 与 CPython 连接起来。

标签: python python-c-api


【解决方案1】:

从 python 2.3 开始,可以使用METH_CLASS 完成。有关示例,请参阅 datetime 模块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多