views:

89

answers:

3

I'm making some win32 string API calls and am assuming that the strings come out as wide strings, which is valid on XP and newer. How can I assert this? Is this a runtime check or a compile-time check?

Am I doing it wrong? Here's an example:

typedef std::basic_string<TCHAR> TString;
inline TString queryRegStringValue(HKEY key, const TString& subkey, 
        const TString defaultValue = TEXT(""))
{
    std::vector<char> out_bytes(256);
    DWORD num_bytes = out_bytes.size();
    DWORD out_type;
    long retval = RegQueryValueEx(key, subkey.c_str(), 0, &out_type, 
        reinterpret_cast<BYTE*>(&out_bytes[0]), &num_bytes); //comes out as a platform string. wide on XP
    if (retval != 0)
        return defaultValue;
    if (num_bytes > 0)
    {
        assert(out_type == REG_SZ);
        BOOST_STATIC_ASSERT(sizeof(TCHAR)==2); //what if someone runs my code on an older system?
        return TString(reinterpret_cast<wchar_t*>(&out_bytes[0]), num_bytes/2); //assumes windows XP (wide string)
    }

    return TEXT("");
}
+1  A: 

I think this MSDN article is what you're looking for. You want to know what version of windows you're on, and adjust your string handling as appropriate? If i misunderstood, please feel free to leave a comment and i'll adjust my answer.

http://msdn.microsoft.com/en-us/library/ms724429.aspx

Caladain
+3  A: 

It is a non-issue. Windows has been a native Unicode operating system for the past 17 years, long before XP was released. David Cutler's brain child, NT 3.1, was Unicode from day one.

In the unlikely case that your program lands on a Window 9x machine, there's still an API layer that can translate your UTF-16 strings to 8-bit chars. There's no point left in using TCHAR for new code development.

Hans Passant
I'm modifying someone else's code which uses TCHAR extensively. Is it better form to just use std::wstring in my code? wstring should be equivalent to TString on widechar platforms so I don't see an issue.
Dustin Getz
I have no idea what a "TString" might be. Another macro? Mixing string typedefs in one legacy source code file won't likely win you any friends.
Hans Passant
i opened a new question: http://stackoverflow.com/questions/3241645/proper-style-for-interfacing-with-legacy-tchar-code
Dustin Getz
+1  A: 

I think what's going on is that when I compile, I compile against the Unicode windows APIs, so if I run my executable on a non-widechar windows, it will fail to run. Thus a runtime check is useless.

I added the compile-time assertion to force a build-error if we compile on a non-widechar platform (pre XP, or pre 2000, or whatever it is) the build will fail. If the assertion weren't there it would fail anyway, but more cryptically.

Dustin Getz