Вопрос

I would like to convert a TCHAR array to a 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));

I need to pass szFileName to a function that expects

const WCHAR *

For completeness I am stating the void that I need to pass szFileName to:

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

However, T2W does not work for me. The compiler says that "_lpa" is not defined, and I don't know where to go on from here. I have tried other conversion methods that I found stated on the net, but they did not work either.

Это было полезно?

Решение

There are functions like

mbstowcs_s()

that convert from char* to 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;

Look here for an article and here for MSDN.

Другие советы

The definition of TCHAR differs depending on if certain preprocessor macros are defined or not. See e.g. this article for the possible combinations.

This means that TCHAR may already be a wchar_t.

You can use the _UNICODE macro to check if you need to convert the string. If you do, then you can use mbstowcs to do the conversion:

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top