anastaciu
anastaciu

Reputation: 23822

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?

Upvotes: 1

Views: 306

Answers (3)

RbMm
RbMm

Reputation: 33754

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

Upvotes: 2

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

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"; 

Upvotes: 2

Adrian Mole
Adrian Mole

Reputation: 51864

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!)

Upvotes: 2

Related Questions