[PyQt] A gobal variable problem in sip

Mathias.Born at gmx.de Mathias.Born at gmx.de
Wed Oct 24 12:56:00 BST 2012


On 24.10.2012, 00:11:13 D.Y Feng wrote:
> I meet a problem in my code:

> hello.h:

> #include<QtCore>

> class Hello : public QObject{
>     Q_OBJECT
> public:
>     Hello(QObject *parent = 0);
>     static int test(){
>         static int i=0;
>         qDebug()<<i++;
>         return 0;
>     }
> };

> hello.cpp:
> #include "hello.h"

> const int i=Hello::test();

> Hello::Hello (QObject *parent)
> {
> }

> hello.sip

> %Module hello

> %Import QtCore/QtCoremod.sip


> class Hello : public QObject {

> %TypeHeaderCode
> #include "hello.h"
> %End

> public:
>      Hello(QObject *parent = 0);
>      static int test();
> };

> I use the const int i=Hello::test(); to invoke test() before main
> function.It's uesful in factory pattern when you want to auto  register driver.

> the python test code
> import hello
> hello.Hello.test1()

> It seems static int i  in test() changed after import hello

Now, I haven't tried that myself yet. On the other hand, I don't see any
problem.

> Breakpoint 1, Hello::test1 () at hello.h:8
> 8           static int test1(){
> (gdb) p i
> $1 = 0
> (gdb) p &i
> $2 = (const int *) 0x7ffff60300d0

This displays the address of your global variable "const int i".

> (gdb) c
> Continuing.
> 0 

> Breakpoint 1, Hello::test1 () at main.h:8
> 8           static int test1(){
> (gdb) p &i
> $3 = (const int *) 0x7ffff60300d0

Again, address of your global variable "const int i".

> (gdb) n
> 10              qDebug()<<i++;
> (gdb) p &i
> $4 = (int *) 0x7ffff62355c0       <---What happen here?

This shows the address of your local static variable "static int i",
which ought to be different.
The names of these objects, which are both "i", come into existence at
different times. While this is perfectly legal C++, it obviously
obfuscates your program. Just naming them differently should already
help a lot.

In summary, I don't think this is an issue with PyQt. But let me quote
Bjarne Stroustrup: "C makes it easy to shoot yourself in the foot; C++
makes it harder, but when you do it blows your whole leg off."

Best Regards,
Mathias Born




More information about the PyQt mailing list