How C/C++ global variables are implemented in python?

瘦欲@ 提交于 2019-12-04 17:10:50

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 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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!