I'm trying to debug print an LPCWSTR
string, but I get a problem during the sprintf
push in the buffer, because it retrieves only the first character from the string.
Here is the code:
HANDLE WINAPI hookedCreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) {
char buffer[1024];
sprintf_s(buffer, 1024, "CreateFileW: %s", lpFileName);
OutputDebugString(buffer);
return trueCreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwFlagsAndAttributes, dwCreationDisposition, hTemplateFile);
}
For example I get CreateFileW: C
or CreateFileW: \
.
How do I properly push it into the buffer?
Thank you.
An LPCWSTR is a 32-bit pointer to a constant string of 16-bit Unicode characters, which MAY be null-terminated.
The C library function int sprintf(char *str, const char *format, ...) sends formatted output to a string pointed to, by str.
You need to tell sprintf() that you pass a wide character string. Use the %ls specifier:
sprintf_s(buffer, 1024, "CreateFileW: %ls", lpFileName);
Do note how unproductive this is. Your code runs on a Unicode operating system. It must convert your char[] string back to a wide string before it can send it to the debugger. That's just wasted CPU cycles with a significant risk of data loss to boot. When you are in Rome, act like a Roman and use wchar_t + wsprintf(). And #define UNICODE so you'll automatically call the fast OutputDebugStringW(), the one that doesn't have to convert the string. The point of using C++ is to write fast code, intentionally making is slow is pointless.
Use swprintf_s which is the version of sprintf_s which is designed for wide-character strings.
You'll also need an array of wchar_t
instead of char
and to use OutputDebugStringW()
Also, note you that swprintf_w
might not be entierly what you want to call. If it encounters a string that is longer than the size you give it, it executes some sort of assertion. I suggest you test this situation specifically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With