wlav / cppyy

Other
391 stars 40 forks source link

Inconsistent results when reading a global array. #113

Open Protract0679 opened 1 year ago

Protract0679 commented 1 year ago

The issue I'm observing is that I execute a function that should look up a piece of data in an array, and sometimes I'll get an incorrect value (usually 0), and other times I'll get the data I expected. I can get different results mid-function by adding some if statements (has to be at least two, one wasn't enough).

I'm running Python 3.9, cppyy 2.4.1, on Windows 10.

What I expect to happen is:

doSomething(2)
Actual=0, Expected=0   <-- Actual and expected are the same
Actual=1, Expected=1
Actual=2, Expected=2
Here <-- Prints happen after the actual/expected prints above
Here

doSomething result: 2  <-- Looking up the correct value in the array

doSomethingElse(2)
doSomethingElse result: 2  <-- Second function without extra if statements also looks up correctly

What I actually see happen is:

Here <---- Prints are out of order
Here

doSomething(2)
Actual=0, Expected=0 
Actual=0, Expected=1 <--- Looking up zeros instead of actual value in array
Actual=0, Expected=2
doSomething result: 2 <--- however it looks up the correct value later on in the function
doSomethingElse(2)
doSomethingElse result: 0 <-- second invocation without extra if statements fails to look up the correct value

This is my test program:

import cppyy

cppyy.cppdef(r"""
struct StructureType {
    uint16_t a;
};
extern StructureType const table[4];

class Plan {
public:
    inline void doSomething(uint16_t const Event);
    inline void doSomethingElse(uint16_t const Event);
};

inline void Plan::doSomething(uint16_t const Event) {
    printf("doSomething(%u)\r\n", Event);
    for (auto i=0; i < 3; ++i) {
        printf("Actual=%u, Expected=%u\r\n", table[i].a, i);
    }

    if (Event == table[Event].a) printf("Here\r\n"); // Comment out these two if statements
    if (Event == table[Event].a) printf("Here\r\n"); // and the result below will be incorrect.

    printf("\r\n");

    printf("doSomething result: %u\r\n", table[Event].a);
}

inline void Plan::doSomethingElse(uint16_t const Event) {
    printf("doSomethingElse(%u)\r\n", Event);

    printf("doSomethingElse result: %u\r\n", table[Event].a);
}

StructureType const table[4] = 
{
    { 0 },
    { 1 },
    { 2 },
    { 3 }
};

class R: public Plan {
public:
    void test(void) {
        this->doSomething(0x2);
        this->doSomethingElse(0x2);
    }    
};
""")

from cppyy.gbl import R

t = R()
t.test()

I tried to reproduce this under Linux and didn't see an issue, it's only happening on Windows.