【问题标题】:C++ TCHAR array to wstring not working in VS2010C ++ TCHAR数组到wstring在VS2010中不起作用
【发布时间】:2013-04-03 11:26:45
【问题描述】:

我想将 TCHAR 数组转换为 wstring。

    TCHAR szFileName[MAX_PATH+1];
#ifdef _DEBUG
    std::string str="m:\\compiled\\data.dat";
    TCHAR *param=new TCHAR[str.size()+1];
    szFileName[str.size()]=0;
    std::copy(str.begin(),str.end(),szFileName);
#else
    //Retrieve the path to the data.dat in the same dir as our data.dll is located
    GetModuleFileName(_Module.m_hInst, szFileName, MAX_PATH+1);
    StrCpy(PathFindFileName(szFileName), _T("data.dat"));
#endif  

wstring sPath(T2W(szFileName));

我需要将szFileName 传递给期望的函数

const WCHAR *

为了完整起见,我声明了我需要将szFileName 传递给:

HRESULT CEngObj::MapFile( const WCHAR * pszTokenVal,  // Value that contains file path
                        HANDLE * phMapping,          // Pointer to file mapping handle
                        void ** ppvData )            // Pointer to the data

但是,T2W 对我不起作用。编译器说that "_lpa" is not defined,我不知道从哪里开始。我尝试了其他我在网上找到的转换方法,但它们也不起作用。

【问题讨论】:

  • 使用TCHAR 的基本规则是,始终使用 tchar 函数和类似的例程。 std::copy 并不是在 TCHARstd::string 之间转换的正确方法。表达LPCTSTR szFileName = _T("m:\\compiled\\data.dat"); 的最简单方法之一您不需要那种复杂的复制代码。如果想要 unicode 变体LPCWSTR szFileName = L"m:\\compiled\\data.dat";

标签: c++ arrays wstring tchar


【解决方案1】:

有类似的功能

mbstowcs_s()

char* 转换为wchar_t*

#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;

char *orig = "Hello, World!";
cout << orig << " (char *)" << endl;

// Convert to a wchar_t*
size_t origsize = strlen(orig) + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);
wcscat_s(wcstring, L" (wchar_t *)");
wcout << wcstring << endl;

查看 here 获取文章,查看 here 获取 MSDN。

【讨论】:

  • TCHAR 由系统头文件自动定义。没有必要自己做。
  • @JoachimPileborg 不知道我在哪里读到的,但在那里似乎很重要
  • 我在某处找到了解决方案:USES_CONVERSION;谁能告诉我这是做什么的?
  • 这是一个macro
【解决方案2】:

TCHAR 的定义会有所不同,具体取决于是否定义了某些预处理器宏。参见例如this article 了解可能的组合。

这意味着TCHAR 可能已经是wchar_t

您可以使用_UNICODE 宏来检查是否需要转换字符串。如果你这样做了,那么你可以使用mbstowcs进行转换:

std::wstring str;

#ifdef _UNICODE
    // No need to convert the string
    str = your_tchar_string;
#else
    // Need to convert the string
    // First get the length needed
    int length = mbstowcs(nullptr, your_tchar_string, 0);

    // Allocate a temporary string
    wchar_t* tmpstr = new wchar_t[length + 1];

    // Do the actual conversion
    mbstowcs(tmpstr, your_tchar_str, length + 1);

    str = tmpstr;

    // Free the temporary string
    delete[] tmpstr;
#endif

【讨论】:

    猜你喜欢
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    相关资源
    最近更新 更多