问题
While i am reading through SWIG Documentation i came through these lines..
C/C++ global variables are fully supported by SWIG. However, the underlying mechanism is somewhat different than you might expect due to the way that Python assignment works. When you type the following in Python
a = 3.4
"a" becomes a name for an object containing the value 3.4. If you later type
b = a
then "a" and "b" are both names for the object containing the value 3.4. Thus, there is only one object containing 3.4 and "a" and "b" are both names that refer to it. This is quite different than C where a variable name refers to a memory location in which a value is stored (and assignment copies data into that location). Because of this, there is no direct way to map variable assignment in C to variable assignment in Python.
To provide access to C global variables, SWIG creates a special object called `cvar' that is added to each SWIG generated module. Global variables are then accessed as attributes of this object.
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.
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
回答1:
It's all about the fact that SWIG has to provide an interface to a library in C/C++ which acts differently.
Let us assume that instead of implementing a cvar
object SWIG simply used PyInt
s 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.
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.
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.
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.
来源:https://stackoverflow.com/questions/18980096/how-c-c-global-variables-are-implemented-in-python