[Qt-interest] QString to TCHAR* and back

Nuno Correia npaulo.nuno at gmail.com
Wed Feb 24 20:19:16 CET 2010


You can do this dynamically, but you need to free the pointer that the
function returns.

TCHAR *QStringToTCharBuffer( QString buffer )
{
    TCHAR *toReturn = (TCHAR*)malloc( ( buffer.size() + 1 ) * sizeof( TCHAR
) );

    if ( buffer.length() != buffer.toWCharArray( toReturn ) )
    {
         delete toReturn;
         return 0;
    }
    toReturn[ buffer.length() ] = '\0'; //don't forget this
    return toReturn;
}


int main(int argc, char *argv[])
{
    TCHAR *c = QStringToTCharBuffer( QString( "Qt is the best!!!" ));
    if ( !c )
    {
        qDebug()<<"Conversion error.";
    }
    delete c;   //don't forget this
    return 0;

On 24 February 2010 17:55, Duane Hebert <spoo at flarn.com> wrote:

> >Try this code, it's work fine for my problem.
>
> >QString to TCHAR
> >    TCHAR buffer[ MAX_PATH ];
> >    filepath.toWCharArray( buffer );
> >    buffer[ filepath.length() ] = '\0';
>
> I had to create a function to do this so I did it like this:
>
> int QStringToTCharBuffer(QString buffer, TCHAR* Array){
>    return buffer.toWCharArray(Array);
> }
>
> The bad part is that the caller has to create the TCHAR* large enough
> to hold the QString, and set the terminator.
>
> I guess, the other option would be to return a std::wstring and have the
> caller do .c_str().
>
> The other way around is fine because we can return a QString.
> _______________________________________________
> Qt-interest mailing list
> Qt-interest at trolltech.com
> http://lists.trolltech.com/mailman/listinfo/qt-interest
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20100224/f90b80fb/attachment.html 


More information about the Qt-interest-old mailing list