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

后端 未结 1 708
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 13:31

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 i

1条回答
  •  伪装坚强ぢ
    2020-12-30 13:44

    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.

    0 讨论(0)
提交回复
热议问题