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);