Search code examples
c++oracle-databaseocci

OCCI - setDataBuffer + vector<struct>


Trying to minimize amount of lines for an OCCI array fetch by storing a struct containing a char buffer into a vector, code below:

    struct Columns { char buffer[1000][300]; };

    int i = 1;
    Columns col;
    ub4* ub = NULL;
    results->setDataBuffer( i++, col.buffer, OCCI_SQLT_STR, sizeof( col.buffer[ 0 ] ), ub );
        vec.push_back( col );

    cout << "Before, vec size: " << vec.size( ) << "\n"; // prints 1, as expected
    while ( results->next( 1000 ) ) {
        for ( size_t j = 0; j < results->getNumArrayRows( ); ++j ) {
            cout << vec[ 0 ].buffer[ j ] << endl;
        }

Now for some reason, this doesnt work. However, if instead of using col.buffer, I create a char buffer[1000][300] and toss that into setDataBuffer then in the cout part do: cout << buffer[j] << endl;

that works just fine. So I'm not really sure where I'm screwing up?

the char buffer is the exact same thing as col.buffer, is it not?

I don't think it matters but struct Columns is defined in the header file.


Solution

  • I guess the setDataBuffer fills the buffer you pass as parameter (which is col.buffer here), then you push it into the vector, so a new struct Columns is allocated by vec and it copy col content. Now col and vec[0] are two different objects.

    Then you call some methods which fills the buffer you first passed to it. So it fills col.buffer, and you read vec[0].buffer, which are different because they are 2 different objects.

    One solution would instead be to do vec.emplace_back(); to create one instance, and then pass vec[0].buffer to setDataBuffer. But be careful with addresses of elements in vectors. If you modify the vector (adding or removing elements) it can reallocate it's content, and the element addresses might change.