0

I work on a project written for MSVCC / Windows, that I have to port to GCC / Linux. The Project has its own String Class, which stores its Data in a QString from Qt. For conversion to wchar_t* there was originally this method (for Windows):

const wchar_t* String::c_str() const
{
    if (length() > 0)
    {
        return (const wchar_t*)QString::unicode();
    }
    else
    {
        return &s_nullString;
    }
}

Because unicode() returns a QChar (which is 16 Bit long), this worked under Windows as wchar_t is 16 Bit there, but now with GCC wchar_t is 32 Bit long, so that doesn't work anymore. I've tried to solve that using this:

const wchar_t* String::c_str() const
{
    if ( isEmpty() )
    {
        return &s_nullString;
    }
    else
    {
        return toStdWString().c_str();
    }
}

The problem with this is, that the object doesn't live anymore when this function returns, so this doesn't work eiter. I think the only way to solve this issue is to either:

  1. Don't use String::c_str() and call .toStdString().c_str() directly
  2. Make GCC treat wchar_t as 16 bit type

Possibility one would mean several hours of needless work to me and I don't know if possiblity 2 is even possible. My question is, how do I solve this issue best? I'd appreciate any useful suggestion. Thank you.

weitho
  • 80
  • 1
  • 9

1 Answers1

0

In my opinion, there are 2 ways :

  1. convert QString to wchar_t* when needed
  2. Let QString to store wchar_t* and return QString::unicode directly

These two functions can convert a QString to std::string and std::wstring
QString::toStdWString
QString::toStdString

To build QString as ucs4 :

#define QT_QSTRING_UCS_4
#include "qstring.h"

This can be used in qt3(qstring.h). I can't find the source of qt4.

OwnWaterloo
  • 1,963
  • 14
  • 11
  • Converting QString to wchar_t* when needed means calling .toStdString().c_str() directly. As I said before, this would be a lot of work and my last option, although that would be the optimal way to solve this. If i understood you right, you mean I should alternatively make Qt return a 32bit wchar, when calling unicode() by adding this #define. This solution sounds good to me. I'll test that. – weitho Dec 08 '09 at 07:37
  • when needed means : we should manage `the lifetime of intermediate object`(string,wstring) very carefully... otherwise, accessing of invalid object or memory leak.Could we put wstring as a member of String class?And update wstring when String::c_str() is called ? – OwnWaterloo Dec 08 '09 at 09:47
  • Thank you. Adding a wstring member to the String class and update it when String::c_str() is called solved my problem. :) – weitho Dec 08 '09 at 12:58