C ++ TCHAR数组使wstring在VS2010中不起作用

时间:2013-04-03 11:26:46

标签: c++ arrays wstring tchar

我想将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,我不知道从哪里开始。我尝试过在网上发现的其他转换方法,但它们也没有用。

2 个答案:

答案 0 :(得分:2)

有像

这样的功能
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,MSDN查看here

答案 1 :(得分:0)

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