简体   繁体   English

使用C API创建在python中声明的python类的实例

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

I want to create an instance of a Python class defined in the __main__ scope with the C API. 我想创建一个使用C API在__main__范围内定义的Python类的实例。

For example, the class is called MyClass and is defined as follows: 例如,该类称为MyClass ,定义如下:

class MyClass:
    def __init__(self):
        pass

The class type lives under __main__ scope. 类类型位于__main__范围内。

Within the C application, I want to create an instance of this class. 在C应用程序中,我想创建此类的实例。 This could have been simply possible with PyInstance_New as it takes class name. 这可能是PyInstance_New可以简单实现的,因为它需要类名。 However this function is not available in Python3. 但是这个功能在Python3中不可用。

Any help or suggestions for alternatives are appreciated. 任何对替代品的帮助或建议都表示赞赏。

Thanks, Paul 谢谢,保罗

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. 完成后只需要DECREF instance ,其他两个是借用的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM