9

我想创建一个__main__使用 C API 在范围内定义的 Python 类的实例。

例如调用类MyClass,定义如下:

class MyClass:
    def __init__(self):
        pass

类类型位于__main__范围内。

在 C 应用程序中,我想创建此类的一个实例。这本来可以很简单,PyInstance_New因为它需要类名。但是,此功能在 Python3 中不可用。

任何有关替代方案的帮助或建议表示赞赏。

谢谢,保罗

4

1 回答 1

20

我相信最简单的方法是:

/* 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", "");

加上当然错误检查。完成后只需要 DECREF instance,其他两个是借来的参考。

于 2009-07-18T15:41:44.240 回答