Re: Is the following little function UNICODE-safe? ...
On Wed, 26 Mar 2008 10:39:59 -0700 (PDT), ".rhavin grobert"
<clqrq@yahoo.de> wrote:
On 26 Mrz., 18:32, ".rhavin grobert" <cl...@yahoo.de> wrote:
I'm trying to write my code in a way that doesn't makes it very hard
to switch later to UNICODE,
but sometimes i've funcs that will be called very often, so they have
to be *fast*
may i expect that a char[] is correctly translated when this fn is
called in a UNICODE-env or is some _T()-magic required?
//-----------------------------------------------------------------------
// get the default extension associated with the files type
LPCTSTR CInfFile::ExtensionGetDefault() const {
DWORD dwDefID = CFZFile::IdentifierGetDefaults(TypeGet());
dwDefID &= 0x00FFFFFF;
return reinterpret_cast<char*>(&dwDefID);
}
thx, -.rhavin;)
ooops, by posting i somehow pasted the old version...
LPCTSTR CInfFile::ExtensionGetDefault() const {
static DWORD dwDefID;
dwDefID = CFZFile::IdentifierGetDefaults(TypeGet());
dwDefID &= 0x00FFFFFF;
return reinterpret_cast<char*>(&dwDefID);
}
That code is not going to compile in a Unicode build, where LPCTSTR is
const wchar_t*, because there is no standard conversion between char* and
wchar_t*. Moreover, you can't just cast a char* to a wchar_t*. You have to
convert narrow strings to wide strings and vice versa using functions like
MultiByteToWideChar and its counterpart, or, in some cases, you can use
CString for this. In addition, this code is limited to three character
extensions and assumes it can store three characters in a DWORD, which is
not the case for Unicode and is an unwise, unnecessary practice no matter
how you look at it. In addition, both functions are equally inefficient.
For the second one to be more efficient, you'd have to initialize the
dwDefId variable when you declare it; that way,
CFZFile::IdentifierGetDefaults(TypeGet()) would be called only the first
time ExtensionGetDefault is called, modulo the inherent race condition in
multithreaded programs.
The simplest approach is to add a CString member to CInfFile. If it's
immutable, and you create multiple instances of CInfFile, you can probably
make it a static member, so there will be only one of them, and it will be
initialized at program startup.
--
Doug Harrison
Visual C++ MVP