PDA

View Full Version : Cast QString array to std::string array



Ishtar
14th July 2011, 13:34
Greetings all

I have a QString array stored on the heap and I would like to cast it into a std::string array and then pass it into a method within a different class.

I have tried the standard way:




QString * arrayPointer;
arrayPointer = new QString [dynamicSize];

ExternalClass test;
test.externalMethod(arrayPointer.toStdString());



This causes the compiler to chock. How do I correctly cast a QString pointer to a std::string pointer?

Many thanks for your help.

Santosh Reddy
14th July 2011, 13:48
I don't see any other way, other than copying all the strings


QString * arrayPointer = new QString[dynamicSize];

std::string * arrayPtr = new std::string[dynamicSize];

for(int i = 0; i < arrayPointer->size(); i++)
*(arrayPtr[i]) = arrayPointer->toStdString();

ExternalClass test;
test.externalMethod(arrayPtr);

delete[] arrayPtr;

mvuori
14th July 2011, 13:50
As far as I know, the pointer conversion is not possible. You need to create a local string with toStdString and pass its address to the method... and perhaps convert it back after the call



QString qstr;
QString * arrayPointer;
arrayPointer = new QString [dynamicSize];
std::string str = arrayPointer->toStdString();
ExternalClass test;
test.externalMethod(&str);

Ishtar
14th July 2011, 17:52
Thank you both.

I kinda expected that and have already done the workaround. I was just wondering if there was some obscure Qt wizardry which could have done it. :cool:

Again, thank you.

Regards
Nikki

ChrisW67
15th July 2011, 08:28
Are you sure to want a pointer to a collection of QStrings or std::string? This is unusual: you would normally use one of the container classes to manage the memory nightmare for you. It is doubly unusual because externalMethod() has no way of knowing how large the array of std::string you pass is.

Have you considered using std::vector<std::string> or QVector/QList?