gpt4 book ai didi

python - 如何将 python C 扩展方法声明为类方法?

转载 作者:太空宇宙 更新时间:2023-11-03 15:17:21 24 4
gpt4 key购买 nike

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

这是相关 C++ 代码的 stub 。

 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 装饰器)对应的是什么上面的例子?

最佳答案

从 python 2.3 开始,可以使用 METH_CLASS 完成.参见 datetime示例模块。

关于python - 如何将 python C 扩展方法声明为类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19939722/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com