我有一个 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/