Pregunta

I have tried the following:

tstringstream s;
s << _T("test") << std::endl;
LPTSTR message = s.str().c_str();
Log(5, _T("Example", message);

Where Log is defined as such:

void Log(DWORD dwSeverity, LPTSTR szAppID, LPTSTR szMsgString, ...)
{

}

But I get the following error:

Error: A value of type "const char *" cannot be used to initialize an entity of type "LPTSTR"

But I'm not sure exactly how to handle this conversion. In my case, I am compiling a multi-byte character-set application using the MSVC++ compiler. Under these conditions, LPTSTR is defined as an LPSTR, which is defined as a CHAR *.

¿Fue útil?

Solución 2

I can see a couple of problems.

First of all here:

LPTSTR message = s.str().c_str();

The call to s.str() returns a temporary which will be destroyed unless you keep it alive. Therefore the address returned by calling c_str() becomes invalid. You need a temporary local:

string str = s.str();
LPCTSTR message = str.c_str();

And since c_str() returns a const C string, you need to declare message to be a const C string too.

The other problem is that your Log function receives a non-const C string, but c_str() returns a const C string. Presumably the Log function does not need to modify the message, so why are you asking for a modifiable buffer. Change Log to receive a const C string:

void Log(..., LPCTSTR szMsgString, ...)

Finally, since this is C++, why are you using C strings at all? It is better to use C++ strings.

Otros consejos

You're hitting const-incompatibility. For some reason, the function Log takes a pointer to mutable data, which is incompatible with the pointer to const data returned by c_str().

If you have the option, change Log to take its parameter as const (I assume it does not actually modify the string passed in):

void Log(DWORD dwSeverity, LPCTSTR szAppID, LPCTSTR szMsgString, ...)

The same way, declare message as LPCTSTR.

Also note that you cannot actually initialise message the way you're doing it now: the string returned by str() is temporary, so you have to store it:

tstring message = s.str();
Log(5, _T("Example", message.c_str());

If Log is outside your control, but you know that it does not modify its arguments, you can use a const_cast:

LPTSTR message = const_cast<LPTSTR>(message.c_str());  // `message` changed as above

If you cannot vouch for what Log does internally, you'll have to create a mutable buffer:

std::vector<TCHAR> buffer(message.begin(), message.end());
buffer.push_back(0);
Log(5, _T("Example", &buffer[0]);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top