开发者

sprintf an LPCWSTR variable

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.


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.


Unless you have a concrete reason to target unicode in this single function (and not, say, in your entire project), it might be wise to use charset-agnostic macros wherever possible:

HANDLE WINAPI hookedCreateFile(LPCTSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) {
 TCHAR buffer[1024];
 _stprintf_s(buffer, 1024, _T("CreateFileW: %s"), lpFileName);
 OutputDebugString(buffer); 
 return trueCreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwFlagsAndAttributes, dwCreationDisposition, hTemplateFile);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜