python中C/C++全局变量是如何实现的? [英] How C/C++ global variables are implemented in python?

查看:45
本文介绍了python中C/C++全局变量是如何实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我阅读 SWIG 文档时,我遇到了这些问题..

While i am reading through SWIG Documentation i came through these lines..

SWIG 完全支持 C/C++ 全局变量.但是,由于 Python 赋值的工作方式,底层机制与您的预期有所不同.当您在 Python 中键入以下内容时
a = 3.4
a"成为包含值 3.4 的对象的名称.如果您稍后输入
b = a
那么a"和b"都是包含值 3.4 的对象的名称.因此,只有一个对象包含 3.4 并且a"和b"都是引用它的名称.这与 C 完全不同,在 C 中变量名指的是存储值的内存位置(并将数据复制到该位置).因此,没有直接的方法可以将 C 中的变量赋值映射到 Python 中的变量赋值.
为了提供对 C 全局变量的访问,SWIG 创建了一个名为cvar"的特殊对象,该对象被添加到每个 SWIG 生成的模块中.然后全局变量作为该对象的属性被访问.

我的问题是需要以上述方式实施.尽管我们以上述方式实现了对象属性,但也将其实现为对象.

My question is what is the need for implementing in the above way. Even though we implemented in the above mentioned way object attributes are also implemented as objects.

请看下面的python代码片段

Please see the below python code snippet

a = 10  
b = a  
a is b  
True  

class sample: 
    pass   

obj = sample()  
obj.a = 10  
obj.b = obj.a  
obj.a is obj.b  
True  

在上述两种情况下,对象分配以相同的方式发生

Here in both the above cases object assignment happening in the same way

推荐答案

SWIG 必须为 C/C++ 中的库提供一个接口,该接口的行为方式不同.

It's all about the fact that SWIG has to provide an interface to a library in C/C++ which acts differently.

让我们假设 SWIG 没有实现 cvar 对象,而是简单地使用 PyInts 等作为生成模块的属性(这就是正常"C 扩展做).然后,当用户从 python 代码中为该变量赋值时,一个 new PyInt 对象被分配给该属性,但 库使用的原始变量是不变,因为模块对象知道它在进行赋值时必须修改 C 全局变量.

Let us assume that instead of implementing a cvar object SWIG simply used PyInts etc. as attributes to the generated modules(which is what "normal" C-extensions do). Then when, from python code, the user assigns a value to the variable a new PyInt object is assigned to that attribute but the original variable used by the library is unchanged, because the module object does not know that it has to modify the C-global variable when doing an assignment.

这意味着,虽然从 python 端用户会看到值的变化,但 C 库不会意识到这种变化,因为全局变量表示的内存位置没有改变它的值.

This means that, while from the python side the user will see the value change, the C library wouldn't be aware of the change because the memory location represented by the global variable didn't change its value.

为了允许用户以从 C/C+ 库中可见的方式设置值,SWIG 必须定义这个 cvar 对象,它在执行赋值时分配值覆盖下库的变量,即它更改包含全局变量值的内存位置的内容.

In order to allow the user to set the values in a manner that is visible from the C/C+ library, SWIG had to define this cvar object, which, when performing assignments, assigns the value to the library's variable under the cover, i.e. it changes the contents of the memory location that contains the value of the global variable.

这可能是为了提供 __setattr____getattr____getattribute__ 的实现,以便 cvar 能够覆盖对属性赋值的行为.

This is probably done providing an implementation of __setattr__ and __getattr__ or __getattribute__, so that cvar is able to override the behaviour of assignment to an attribute.

这篇关于python中C/C++全局变量是如何实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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