开发者

How to define a new type (class) in Python using C API?

开发者 https://www.devze.com 2023-01-02 08:40 出处:网络
I am trying to use the Python C API to define a new class inside a module that would expose certain functionality written in C to Python code. I specifically want to have it in the form of a class and

I am trying to use the Python C API to define a new class inside a module that would expose certain functionality written in C to Python code. I specifically want to have it in the form of a class and not a set of module functions.

However, I can't find anything regarding this particular task in the official documentation. The closest I could find is PyClass_New function (in the Python.h header) but it is not mentioned anywhere in the official docs, so I assume it is not supposed to be used.

开发者_Python百科

So, what is the proper way to define a new Python class from C code?

Thanks.


This part of the docs (and surrounding ones) should give you most of the info you need. The xxsubtype.c sources provide one example module that defines a new class (as a subclass of list, to show precisely how to do that, too) and xxmodule.c shows (among many other things) also how to define a new type.


 static PyObject* Request_new(PyTypeObject *type, PyObject *args, PyObject *kwds) 

May help you, then you can declare PyTypeObject variable to define a new class.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号