Friday, July 3, 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 ?


2 comments:

Anonymous said...

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

Generic Viagra said...

It is good to learn new things everyday!
In fact, there are lots of features shown in here which I had no idea they existed. This way, I have another chance to give a try to new things such as theses.
Eventually, I will be coming back to see if there is something up.
Thanks for everything and have a nice day! just as I did when I found this wonderful site