Turn std :: vector objects into an array of structures

I have a VS2008 C ++ program where I wrap a C API for use in a C ++ program. The C API expects an array of TABLE_ENTRY values, as shown below.

Besides copying data from each MyClass structure to TABLE_ENTRY's new structure MyClassCollection::GetTable(), is there a way to get the functionality I'm looking for?

Thanks PaulH

struct TABLE_ENTRY {
    const char* description;
    DWORD value;
};

class MyClass
{
public:
    MyClass( const char* desc, DWORD value ) : 
        description( desc ),
        some_value( 1 )
    {
    };

    TABLE_ENTRY* GetTable()
    {
        entry_.description = description.c_str();
        entry_.value = some_value;
        return &entry_;
    };

    TABLE_ENTRY entry_;
    std::string description;
    DWORD some_value;
};

class MyClassCollection
{
public:
    TABLE_ENTRY* GetTable()
    {
        return collection_.front()->GetTable();
    };

    void Add( MyClass* my_class )
    {
        collection_.push_back( my_class );
    }
private:
    std::vector< MyClass* > collection_;
};

int _tmain( int argc, _TCHAR* argv[] )
{
    MyClass class1( "class1", 1 );
    MyClass class2( "class2", 2 );

    MyClassCollection collection;
    collection.Add( &class1 );
    collection.Add( &class2 );

    TABLE_ENTRY* table = collection.GetTable();

    // table is to be used by the C API. Therefore, these next
    // calls should function as shown.
    TABLE_ENTRY entry1 = table[ 0 ]; // should be class1 table (works)
    TABLE_ENTRY entry2 = table[ 1 ]; // should be class2 table (full of junk)

    return 0;
}
+3
source share
4 answers

I would like to migrate to vector<TABLE_ENTRY>and pass &entries[0]in API C.

TABLE_ENTRY ++. , API, . , TABLE_ENTRY , , direct char* , std::string. ( ), .

+1

: ( ++ 03, ++ 98 )

&vec[0]

, , .

+1

(!= char *), void *, ( VMT )

0

By requesting an array of TABLE_ENTRY, the API lets you know that it expects data to be ordered in memory this way. It is not possible to meet API expectations with data located in different ways, so you are out of luck.

0
source

Source: https://habr.com/ru/post/1735134/


All Articles