什么是PyClass_New相当于在Python 3? [英] What is the PyClass_New equivalent in Python 3?
本文介绍了什么是PyClass_New相当于在Python 3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
previously我已经用C API一些Python类。当我要建立旧项目与Python 3+它提供了以下编译错误
PyClass_New没有在这个范围内声明
Py_InitModule没有在这个范围内声明
什么是等价?
的PyObject * pClassDic = PyDict_New();
*的PyObject = pClassName PyBytes_FromString(MyClass的);
*的PyObject = pClass PyClass_New(NULL,pClassDic,pClassName);
解决方案
如果你不想去通过设置你的对象和类型结构的麻烦,你应该能够通过调用创建一个新的类Python的类型(名称,碱,字典)
从C:
的PyObject * pClassName = PyBytes_FromString(MyClass的);
的PyObject * pClassBases = PyTuple_New(0); //为基地的一个空的元组等同于`(对象)`
的PyObject * pClassDic = PyDict_New();// pClass =类型(pClassName,pClassBases,pClassDic)
的PyObject * pClass = PyObject_CallFunctionObjArgs(PyType_Type,pClassName,pClassBases,pClassDic,NULL);Py_CLEAR(pClassName);
Py_CLEAR(pClassBases);
Py_CLEAR(pClassDic);
Previously I have created some Python classes using C API. When I'm going to build the old project with Python 3+ it gives following compile error
PyClass_New was not declared in this scope Py_InitModule was not declared in this scope
What are the equivalents?
PyObject *pClassDic = PyDict_New();
PyObject *pClassName = PyBytes_FromString("MyClass");
PyObject *pClass = PyClass_New(NULL, pClassDic, pClassName);
解决方案
If you don't want to go through the hassle of setting up your object and type structs, you should be able to create a new class by calling Python's type(name, bases, dict)
from C:
PyObject *pClassName = PyBytes_FromString("MyClass");
PyObject *pClassBases = PyTuple_New(0); // An empty tuple for bases is equivalent to `(object,)`
PyObject *pClassDic = PyDict_New();
// pClass = type(pClassName, pClassBases, pClassDic)
PyObject *pClass = PyObject_CallFunctionObjArgs(PyType_Type, pClassName, pClassBases, pClassDic, NULL);
Py_CLEAR(pClassName);
Py_CLEAR(pClassBases);
Py_CLEAR(pClassDic);
这篇关于什么是PyClass_New相当于在Python 3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文