使用C API创建Python类的实例
我想用C语言的接口来创建一个在__main__
范围内定义的Python类的实例。
比如,这个类叫做MyClass
,定义如下:
class MyClass:
def __init__(self):
pass
这个类的类型是在__main__
范围内的。
在C程序中,我想创建这个类的一个实例。原本可以简单地使用PyInstance_New
来实现,因为它需要类名作为参数。不过在Python3中,这个函数是不可用的。
如果有人能提供帮助或替代方案,我将非常感激。
谢谢,Paul
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", "");
当然,还要进行错误检查。当你用完instance
后,只需要减少它的引用计数,其他两个是借来的引用。