Thursday, 2 July 2009

Visual studio 2005 typecast problem with legacy code

Problem :

I'm trying to get some old visual studio 6 code to compile in visual studio 2005. I'm getting the following compile time error:

"2>c:\documents and settings\user\desktop\xlis
tctrl_demo\xlistctrl\xtrace.h(74) : error C2440: '=' : cannot convert from 'const wchar_t *' to 'LPTSTR' "

This is the offending function:
            if (!XTRACE_SHOW_FULLPATH)
            {
                  cp = _tcsrchr(m_file, _T('\\'));
                  if (cp)
                        cp++;
            }


Solution :

In Visual Studio 2005 C++, functions that previously took a variable declared as const no longer do so.  For example, the following compiles using Visual Studio 2003:

const __wchar_t __pin *strPrinterName = ::PtrToStringChars(printerName);

BOOL result = ::OpenPrinter(strPrinterName, mJobHandle, NULL);

But, with Visual Studio 2005 results in:

error C2664: 'OpenPrinterW' : cannot convert parameter 1 from 'const wchar_t __pin *' to 'LPWSTR'
Conversion loses qualifiers

To get around this, you need to explicitly cast away the const-ness:

const __wchar_t __pin *strPrinterName = ::PtrToStringChars(printerName);

BOOL result = ::OpenPrinter((LPWSTR) strPrinterName, mJobHandle, NULL);

Removing const from the first line won't help because PtrToStringChars is declared as returning a const.

So, the solution is

This is the offending function:
            if (!XTRACE_SHOW_FULLPATH)
            {
                  cp = (LPWSTR)_tcsrchr(m_file, _T('\\'));
                  if (cp)
                        cp++;
            }

- Mihir Patel.

Ref :
1. http://www.experts-exchange.com/Programming/Languages/CPP/Q_22734496.html
2. http://geekswithblogs.net/.NETonMyMind/archive/2006/10/01/92866.aspx

Note : www.experts-exchange.com is not a way to go.. Is anyone has mirror site or any other reference like this site ?


1 comment:

  1. Wait, Experts Exchange gives you a solution but is "not a way to go"? Sounds like it's the way to go to me.

    ReplyDelete