c++ - 将对象的 std::vector 转换为结构数组

标签 c++

我有一个 VS2008 C++ 程序,我在其中包装了一个 C API 以便在 C++ 程序中使用。 C API 需要一个 TABLE_ENTRY 值数组,如下所示。

除了将数据从每个 MyClass 结构复制到 MyClassCollection::GetTable() 中的新 TABLE_ENTRY 结构之外,还有其他方法可以获得我正在寻找的功能吗?

谢谢, 保罗H

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's table (works)
    TABLE_ENTRY entry2 = table[ 1 ]; // should be class2's table (full of junk)

    return 0;
}

最佳答案

我会去复制到 vector<TABLE_ENTRY>并通过 &entries[0]到 C API。

而且,我不会存储 TABLE_ENTRY s 在你的 C++ 类中。我只会像您调用 API 那样制作它们,然后将它们扔掉。那是因为 TABLE_ENTRY复制您从中复制的对象,并且它正在存储一个直接 char*指向内存由 std::string 管理的字符串的指针。如果您修改源字符串(并导致重新分配),就会有一个悬空指针。

关于c++ - 将对象的 std::vector 转换为结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2367293/

相关文章:

c++ - 转换在 Visual Studio 2015 中不明确,但在 clang 中没有

c++ - 使用数组 C++ 的动态堆栈

c++ - 从 C 扩展跟踪 CPython 对象的生命周期

c++ - 空数组声明 - 奇怪的编译器行为

c++ - 对另一个类中的一个类使用重载运算符

c++ - 在 C++ 中存储和打印 10+ 位整数

c++ - 默认参数和参数包之间的交互(GCC 和 clang 不同意)

c++ - __m128d 不是原生对齐的吗?

c++ - Protobuf union 消息异常

c++ - clrscr();等效于 Code::Blocks