Create instance of a python class , declared in python, with C API

为君一笑 提交于 2019-11-30 15:15:17

问题


I want to create an instance of a Python class defined in the __main__ scope with the C API.

For example, the class is called MyClass and is defined as follows:

class MyClass:
    def __init__(self):
        pass

The class type lives under __main__ scope.

Within the C application, I want to create an instance of this class. This could have been simply possible with PyInstance_New as it takes class name. However this function is not available in Python3.

Any help or suggestions for alternatives are appreciated.

Thanks, Paul


回答1:


I believe the simplest approach is:

/* get sys.modules dict */
PyObject* sys_mod_dict = PyImport_GetModuleDict();
/* get the __main__ module object */
PyObject* main_mod = PyMapping_GetItemString(sys_mod_dict, "__main__");
/* call the class inside the __main__ module */
PyObject* instance = PyObject_CallMethod(main_mod, "MyClass", "");

plus of course error checking. You need only DECREF instance when you're done with it, the other two are borrowed references.



来源:https://stackoverflow.com/questions/1147452/create-instance-of-a-python-class-declared-in-python-with-c-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!