简体   繁体   中英

Can't assign named pipe name to LPTSTR variable

I'm getting used to win32 API shenanigans but it's tiresome, the problem I face this time regards the assignemt of a name of a named pipe, this is what I'm doing:

LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\mynamedpipe"); 

This is verbatim from MSDN webpages , and surprise, surprise, this doesn't compile and issues the following error:

E0144 a value of type "const wchar_t *" cannot be used to initialize an entity of type "LPTSTR"

Now a cast will solve the assignment but then I get a 109 error, which is, you guessed it, ERROR_BROKEN_PIPE .

How should I solve this?

LPTSTR is the non-const version. You're trying to acquire a non-const pointer to a string literal.

This used to be valid C++ (it still is valid C, hence the sample), but it was very dangerous, so they made illegal in C++11. You either want:

wchar_t const* lpszPipename = L"\\\\.\\pipe\\mynamedpipe"; 

or

wchar_t pipename[] = L"\\\\.\\pipe\\mynamedpipe"; 

The problem is that, despite claims to the contrary, the examples given in the WinAPI documentation are written in (mostly) C, not C++. Also, the use of string literals to initialize non- const character pointers is no longer allowed in C++ (since C++11).

So, replace:

LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\mynamedpipe");

with:

TCHAR lpszPipename[] = TEXT("\\\\.\\pipe\\mynamedpipe");

(Whether or not that will fix your ERROR_BROKEN_PIPE is another matter, though!)

CreateNamedPipe take pointer to constant string ( LPCSTR or LPCWSTR) in place pipe name. so and do direct

CreateNamedPipe(TEXT("\\\\.\\pipe\\mynamedpipe"), ..)

i not view any reason for

LPCTSTR lpszPipename = TEXT("\\\\.\\pipe\\mynamedpipe");
CreateNamedPipe(lpszPipename , ..)

however if by some reason use lpszPipename - it must be declared as pointer to constant string. LPCTSTR lpszPipename instead LPTSTR lpszPipename


possible and next solution - declare in global scope

static const WCHAR gPipename[] = L"\\\\.\\pipe\\mynamedpipe";

and use it, on binary level CreateNamedPipeW(L"\\\\.\\pipe\\mynamedpipe"), ..) and CreateNamedPipeW(gPipename, ..) produce the same code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM