Re: LPCTSTR and CString
"mido1971" <mido1971@discussions.microsoft.com> ha scritto nel messaggio
news:32D88001-5DA4-4CB4-A97A-BF26F7AE4B36@microsoft.com...
extern "C" AFX_EXT_API LPCTSTR WINAPI GetString()
{
LPCTSTR lpcstr ;
CString str = _T("xxx");
lpcstr =str;
return lpcstr ;
}
The above code is wrong.
In fact, CString 'str' instance is built on the stack (it is a local
automatic variable). So, when function GetString() terminates, this variable
'str' (which is local to function body) is *destroyed*.
So, its content (the string) is lost.
What is safe to do is to return a CString instance:
CString GetString()
{
CString str = ...
....
return str;
}
another thing why i cant use CString in post of LPCTSTR if i use it i got
this warning
warning C4190: '<Unknown>' has C-linkage specified, but returns UDT
'CString' which is incompatible with C
The warning is clear: you say that your function as a C interface, but you
are using a C++ class (CString) in that interface, and so you are
introducing a C++ element (CString class) into a pure C interface, and that
is not possible.
If you really want a C interface, you should consider passing the buffer
from the caller (i.e. the caller allocates a string buffer, and the called
function fills it):
<code>
extern "C" AFX_EXT_API void WINAPI GetString( TCHAR * destBuffer, size_t
destSizeInBytes )
{
// Check destination buffer
ASSERT( destBuffer != NULL );
ASSERT( destSizeInBytes != 0 );
CString str;
....
work with your str instance ...
...
//
// Return string to the caller,
// copying the string into caller's buffer.
//
// Use a safe string function to avoid buffer overruns.
//
StringCbCopy(
destBuffer, // destination buffer
destSizeInBytes, // its size in bytes
str // source string
);
}
</code>
You can use the above code like this:
// Get string into local buffer
TCHAR theString[ 300 ];
GetString( theString, sizeof(theString) );
HTH,
Giovanni