创建一个Python类,在python宣布的情况下,与C API [英] Create instance of a python class , declared in python, with C API

查看:316
本文介绍了创建一个Python类,在python宣布的情况下,与C API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建中定义的Python类的实例 __与C API主要__ 范围。

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

例如,该类称为 MyClass的键,定义如下:

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

class MyClass:
    def __init__(self):
        pass

类的类型住在 __ __主要范围。

在C应用程序,我想创建这个类的一个实例。这可能是简单地可能的 PyInstance_New ,因为它需要的类名。然而,这功能不可用在Python3。

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.

任何帮助或建议的替代品是AP preciated。

Any help or suggestions for alternatives are appreciated.

谢谢,保罗

推荐答案

我相信最简单的方法是:

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

当然,错误检查加。你只需要DECREF 实例当你用它做,另外两个是借来的引用。

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

这篇关于创建一个Python类,在python宣布的情况下,与C API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆