1

アンマネージ C++ ライブラリから文字列ベクトルをラップする必要があり、そのためには avector<string>を aに変換する必要がありchar***ます。この変換には、関数を使用しています。ただし、その中にあるように見えても、out out ポインターの値は無効に変更されました。

以下に簡単な例を示します。

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ますか? それを修正する方法は?

どうもありがとう。

4

2 に答える 2

1

ベクトルを参照渡しする必要があります

void exportVector(vector<string> &vect, char*** pData, int* pSize)

また、ここで strdup を使用する必要があります。

charVect[i] = const_cast<char*>(vect[i].c_str());
//should be
charVect[i] = strdup(vect[i].c_str());

最後に、

vector<char*> charVect = vector<char*>(vect.size());
*pData = &charVect[0];

segfault の原因は charVect が関数の最後で破棄されるため、これらの行を削除して次のようにする必要があります。

(*pData) = new char*[vect.size()];
// Copy and cast elements of given vector into chars
for(unsigned int i = 0; i < vect.size() ; i++)
{
    (*pData)[i] = strdup(vect[i].c_str());
}
于 2013-11-14T10:06:40.160 に答える