我需要从非托管 C++ 库中包装一个字符串向量,为此我必须将 a 转换vector<string>
为char***
. 对于这种转换,我使用了一个函数。但是,即使它看起来就在其中,一旦指针值更改为无效。
这是一个简单的例子:
int main() {
cout << "Start of the program" << endl;
vector<string> vStr = vector<string>();
vStr.push_back("ABC");
vStr.push_back("DEF");
vStr.push_back("GHI");
vStr.push_back("JKL");
vStr.push_back("MNO");
vStr.push_back("PQR");
char*** pStr = new char**();
int* pLength = new int();
cout << " > before export" << endl;
exportVector(vStr, pStr, pLength);
cout << " < after export" << endl;
cout << "\t pLength value = " << *pLength << endl;
for (unsigned int i = 0 ; i < vStr.size(); i++)
{
cout <<"\t pStr "<< i << ": " << vStr[i] << " to ";
for(unsigned int j = 0; j < 3; ++j)
{
cout << "-" << pStr[0][i][j];
}
cout << "-"<< endl;
}
cout << "End of the program" << endl;
delete pStr;
delete pLength;
return 0;
}
void exportVector(vector<string> vect, char*** pData, int* pSize)
{
vector<char*> charVect = vector<char*>(vect.size());
//cout << "\t charVect.size() = " << charVect.size() << endl;
// Copy and cast elements of given vector into chars
for(unsigned int i = 0; i < vect.size() ; i++)
{
charVect[i] = const_cast<char*>(vect[i].c_str());
}
*pData = &charVect[0];
*pSize = vect.size();
cout << "\t pSize = " << *pSize << endl;
for (unsigned int i = 0 ; i < vect.size(); i++)
{
cout <<"\t pData "<< i << ": ";
for(unsigned int j = 0 ; j < 3 ; ++j)
{
cout << "-" << pData[0][i][j];
}
cout << "-"<< endl;
}
}
我进入控制台:
Start of the program
> before export
pSize = 6
pData 0: -A-B-C-
pData 1: -D-E-F-
pData 2: -G-H-I-
pData 3: -J-K-L-
pData 4: -M-N-O-
pData 5: -P-Q-R-
< after export
pLength value = 6
pStr 0: ABC to -Ä- -i-
pStr 1: DEF to - - -i-
pStr 2: GHI to -G-H-I-
pStr 3: JKL to -J-K-L-
pStr 4: MNO to -M-N-O-
pStr 5: PQR to -P-Q-R-
End of the program
如何解释exportVector
函数内部和外部值的差异?如何纠正它?
非常感谢。