Convert/Cast FString to LPTSTR (Windows.h) ?

I am trying to use named windows pipe in c++ Project.

I followed this example from MSDN

In particular I used this CreateFile function from windows.h given in the example



      hPipe = CreateFile( 
         lpszPipename,   // pipe name 
         GENERIC_READ |  // read and write access 
         GENERIC_WRITE, 
         0,              // no sharing 
         NULL,           // default security attributes
         OPEN_EXISTING,  // opens existing pipe 
         0,              // default attributes 
         NULL);          // no template file 

The problem here is the first argument of the CreateFile function the signature indicates it needs to be a LPCTSTR :

I am unable to convert a FString from UE4 to LPCTSTR , I tried multiple ways like ANSI_TO_CHAR , *FString and *TEXT() but none of them are compatible

Doing an explicit type conversion from to LPCTSTR or LPTSTR from *FString results in a Invalid pipe handle.

How should I use the Create File function with UE4?

You can actually just use a FPlatformNamedPipe object (Runtime/Core/Public/HAL/PlatformNamedPipe.h) which will wrap all that code for you in a platform independent way and will make the call to CreateFile for you. If you still want to manage that pipe yourself, you can look at Runtime/Core/Private/Windows/WindowsPlatformNamedPipe.cpp which calls CreateFile and just uses the * operator on an FString to pass it to the windows API call.

hi commander sherpard, if you try to open the serial port you can use CreateFileW instead regular CreateFile, anyway i use wstring, check this code:



FString fscom = "COM" + FString::FromInt(2);
string scom(fscom.c_str());
wstring wscom;
wscom.assign(scom.begin(),scom.end());
//and finally
HANDLE serial = CreateFileW(wscom.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);


this works for me, hope helps you

Note: as a little tip, try to right click to LPCTSTR and peek definition, this show you the typedef for it, and the go again to find the common ancestor, in this case your will see is the same as LPCWSTR and PCTSTR also for WCHAR and in the very end is wchar_t*, so thats way i use wstring

Cheers!

1 Like

I know this is an old threat, but for those who are looking for a solution:

In 4.26 and 4.27 (and maybe earlier versions too) there is no c_str() member of FString. However, if you are using the WCHAR versions (LPCWSTR) you can use *FStringVar.

FString MyFile="Test";
HANDLE serial = CreateFileW(*MyFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

Richard