将 lptstr 转换为 char*

发布于 2024-07-10 00:16:59 字数 70 浏览 4 评论 0原文

有人知道如何在 C++ 中将 LPTSTR 类型转换为 char * 吗?

Would anyone happen to know how to convert type LPTSTR to char * in C++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

不羁少年 2024-07-17 00:16:59

取决于它是否显示为 Unicode。 如果不是 Unicode,则 LPTSTR 是 char*,如果是,则 LPTSTR 是 w_char*。

此处进行了更好的讨论(接受的答案值得一读)

Depends if it is Unicode or not it appears. LPTSTR is char* if not Unicode, or w_char* if so.

Discussed better here (accepted answer worth reading)

不知在何时 2024-07-17 00:16:59

这里有很多方法可以做到这一点。 MFC 或ATL 的CString、ATL 宏或Win32 API。

LPTSTR szString = _T("Testing");
char* pBuffer;

您可以使用 ATL 宏来转换:

USES_CONVERSION;
pBuffer = T2A(szString);

CString:

CStringA cstrText(szString);

或 Win32 API WideCharToMultiByte(如果定义了 UNICODE)。

Here are a lot of ways to do this. MFC or ATL's CString, ATL macros, or Win32 API.

LPTSTR szString = _T("Testing");
char* pBuffer;

You can use ATL macros to convert:

USES_CONVERSION;
pBuffer = T2A(szString);

CString:

CStringA cstrText(szString);

or the Win32 API WideCharToMultiByte if UNICODE is defined.

瞄了个咪的 2024-07-17 00:16:59

如果您的编译器字符设置设置为 Unicode 字符集,则 LPTSTR 将被解释为 wchar_t*。 在这种情况下,需要将 Unicode 字符转换为多字节字符。
(在 Visual Studio 中,设置位于 Project Properties\Configuration Properties\General\Character Set)

下面的示例代码应该给出一个想法:

#include <windows.h>

/* string consisting of several Asian characters */
LPTSTR wcsString = L"\u9580\u961c\u9640\u963f\u963b\u9644";
//LPTSTR wcsString = L"OnlyAsciiCharacters";

char* encode(const wchar_t* wstr, unsigned int codePage)
{
    int sizeNeeded = WideCharToMultiByte(codePage, 0, wstr, -1, NULL, 0, NULL, NULL);
    char* encodedStr = new char[sizeNeeded];
    WideCharToMultiByte(codePage, 0, wstr, -1, encodedStr, sizeNeeded, NULL, NULL);
    return encodedStr;
}

wchar_t* decode(const char* encodedStr, unsigned int codePage)
{
   int sizeNeeded = MultiByteToWideChar(codePage, 0, encodedStr, -1, NULL, 0);
   wchar_t* decodedStr = new wchar_t[sizeNeeded ];
   MultiByteToWideChar(codePage, 0, encodedStr, -1, decodedStr, sizeNeeded );
   return decodedStr;
}

int main(int argc, char* argv[])
{
   char* str = encode(wcsString, CP_UTF8); //UTF-8 encoding
   wchar_t* wstr = decode(str, CP_UTF8);
   //If the wcsString is UTF-8 encodable, then this comparison will result to true.
   //(As i remember some of the Chinese dialects cannot be UTF-8 encoded 
   bool ok = memcmp(wstr, wcsString, sizeof(wchar_t) * wcslen(wcsString)) == 0; 
   delete str;
   delete wstr;

   str = encode(wcsString, 20127); //US-ASCII (7-bit) encoding
   wstr = decode(str, 20127);
   //If there were non-ascii characters existing on wcsString, 
   //we cannot return back, since some of the data is lost
   ok = memcmp(wstr, wcsString, sizeof(wchar_t) * wcslen(wcsString)) == 0; 
   delete str;
   delete wstr;
}

另一方面,如果您的编译器字符设置设置为 Multibyte,则 LPTSTR 将被解释为 char*

在这种情况下:

LPTSTR x = "test";
char* y;
y = x;

另请参阅:

有关 wchar_t 转换的另一个讨论:如何正确使用 WideCharToMultiByte
MSDN 文章:http://msdn.microsoft。 com/en-us/library/dd374130(v=vs.85).aspx
有效代码页标识符:http://msdn。 microsoft.com/en-us/library/dd317756(v=vs.85).aspx

If your compiler Character Setting is set to Unicode Character Set, then LPTSTR will be interpreted as wchar_t*. In that case Unicode to Multibyte character conversion is required.
(In Visual Studio, setting is located at Project Properties\Configuration Properties\General\Character Set)

The sample code below should give an idea:

#include <windows.h>

/* string consisting of several Asian characters */
LPTSTR wcsString = L"\u9580\u961c\u9640\u963f\u963b\u9644";
//LPTSTR wcsString = L"OnlyAsciiCharacters";

char* encode(const wchar_t* wstr, unsigned int codePage)
{
    int sizeNeeded = WideCharToMultiByte(codePage, 0, wstr, -1, NULL, 0, NULL, NULL);
    char* encodedStr = new char[sizeNeeded];
    WideCharToMultiByte(codePage, 0, wstr, -1, encodedStr, sizeNeeded, NULL, NULL);
    return encodedStr;
}

wchar_t* decode(const char* encodedStr, unsigned int codePage)
{
   int sizeNeeded = MultiByteToWideChar(codePage, 0, encodedStr, -1, NULL, 0);
   wchar_t* decodedStr = new wchar_t[sizeNeeded ];
   MultiByteToWideChar(codePage, 0, encodedStr, -1, decodedStr, sizeNeeded );
   return decodedStr;
}

int main(int argc, char* argv[])
{
   char* str = encode(wcsString, CP_UTF8); //UTF-8 encoding
   wchar_t* wstr = decode(str, CP_UTF8);
   //If the wcsString is UTF-8 encodable, then this comparison will result to true.
   //(As i remember some of the Chinese dialects cannot be UTF-8 encoded 
   bool ok = memcmp(wstr, wcsString, sizeof(wchar_t) * wcslen(wcsString)) == 0; 
   delete str;
   delete wstr;

   str = encode(wcsString, 20127); //US-ASCII (7-bit) encoding
   wstr = decode(str, 20127);
   //If there were non-ascii characters existing on wcsString, 
   //we cannot return back, since some of the data is lost
   ok = memcmp(wstr, wcsString, sizeof(wchar_t) * wcslen(wcsString)) == 0; 
   delete str;
   delete wstr;
}

On the other hand, if your compiler Character Setting is set to Multibyte, then LPTSTR will be interpreted as char*.

In that case:

LPTSTR x = "test";
char* y;
y = x;

Also see:

Another discussion about wchar_t conversion: How do you properly use WideCharToMultiByte
MSDN Article: http://msdn.microsoft.com/en-us/library/dd374130(v=vs.85).aspx
Valid Code Page Identifiers: http://msdn.microsoft.com/en-us/library/dd317756(v=vs.85).aspx

陈甜 2024-07-17 00:16:59
char * pCopy = NULL;
if (sizeof(TCHAR) == sizeof(char))
{
    size_t size = strlen(pOriginal);
    pCopy = new char[size + 1];
    strcpy(pCopy, pOriginal);
}
else
{
    size_t size = wcstombs(NULL, pOriginal, 0);
    pCopy = new char[size + 1];
    wcstombs(pCopy, pOriginal, size + 1);
}
char * pCopy = NULL;
if (sizeof(TCHAR) == sizeof(char))
{
    size_t size = strlen(pOriginal);
    pCopy = new char[size + 1];
    strcpy(pCopy, pOriginal);
}
else
{
    size_t size = wcstombs(NULL, pOriginal, 0);
    pCopy = new char[size + 1];
    wcstombs(pCopy, pOriginal, size + 1);
}
小情绪 2024-07-17 00:16:59

好的,假设您必须使用 Unicode。 你使用一些像 LookupAccountSid 这样的函数,它们是你的程序运行所必需的 - 但它们返回 LPTSTR 来获取你需要作为字符串处理的重要信息(无论出于何种原因 - 它是编程,会发生这样的事情)

现在,如果你使用多字节 - 这不是问题。 但有一个方法可以解决它。 这是我的方法,诚然是草率的。 但尽管如此,您应该能够看到它是如何工作的。

const std::wstring &wstring = AcctName; // AcctName being my LPTSTR string
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstring[0], (int)wstring.size(), NULL, 0, NULL, NULL);
std::string strTo(size_needed, 0);

WideCharToMultiByte(CP_UTF8, 0, & wstring[0], (int)wstring[0], &strTo[0], size_needed, NULL, NULL);

char* charUserName = new char[strTo.size() + 1];

// Set charUserName via copying
std::copy(strTo.begin(), strTo.end(), charUserName);
charUserName[strTo.size()] = '\0';

SetUPI(charUserName); // charUserName being my converted char * - 
// You don't need this last part - but this is an example of passing to method
// that takes a string

有任何问题就问吧。 我意识到这是一篇旧帖子 - 但我喜欢为将来来看的人发帖。 (像我这样的人)

OK, so lets say that you HAVE to use Unicode. And you use some functions like LookupAccountSid, that are required for your program to function - but they return LPTSTR for important information you NEED to process as a string (for whatever reason - it's programming, stuff like this happens)

Now, if you were using multibyte - this wouldn't be an issue. But there is a way to solve it. This is my method and is admittedly sloppy. But nonetheless you should be able to see how it works.

const std::wstring &wstring = AcctName; // AcctName being my LPTSTR string
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstring[0], (int)wstring.size(), NULL, 0, NULL, NULL);
std::string strTo(size_needed, 0);

WideCharToMultiByte(CP_UTF8, 0, & wstring[0], (int)wstring[0], &strTo[0], size_needed, NULL, NULL);

char* charUserName = new char[strTo.size() + 1];

// Set charUserName via copying
std::copy(strTo.begin(), strTo.end(), charUserName);
charUserName[strTo.size()] = '\0';

SetUPI(charUserName); // charUserName being my converted char * - 
// You don't need this last part - but this is an example of passing to method
// that takes a string

Any questions just ask. I realise this is an old post - but I like to post for people in the furture that come looking. (people like me)

℡寂寞咖啡 2024-07-17 00:16:59

我希望这对某人有帮助,因为我花了一段时间才弄清楚如何做到这一点。

首先,LPTSTR是指针类型,它基本上等同于TCHAR*(假设包含) 。
请注意,TCHAR 的大小因字符编码类型而异。 即如果定义了 unicode,则 TCHAR 等于 wchar_t,否则为 char

当然,如果将宽字符转换为普通的char,则只能保留LSB,并且可能会丢失一些数据。 这对我来说有点恼火。 所以我写了下面的代码。 它的主要优点是进行转换时不会丢失任何数据。

顺便说一下,如果您同意数据丢失,那么 wcstombs完成这项工作。

#include <cstring>
#include <algorithm>
#include <tchar.h>

void lptstr2str(LPTSTR tch, char* &pch) // or (TCHAR* tch, char* &pch)
{
#ifndef UNICODE
    std::memcpy(pch, tch, strlen(tch) + 1);
#else
    size_t n =
        sizeof(TCHAR) / sizeof(char)* wcsnlen(tch, std::string::npos);
    pch = new char[n + 1];
    std::memcpy(pch, tch, n + 1);
    int len = n - std::count(pch, pch + n, NULL);
    std::remove(pch, pch + n, NULL);
    pch[len] = NULL;
#endif
}

I hope this helps someone, because it took me a while to figure out how to do it.

First of all, LPTSTR is of pointer type and it is basically equivalent to TCHAR* (assuming that <tchar.h> is included).
Note that the size of TCHAR varies based of the character encoding type. i.e. if unicode is defined, TCHAR is equal to wchar_t, otherwise it is char.

Naturally, if you convert a wide character to a normal char, you can only keep the LSB and may lose some data. This was somehow irritating for me. so I wrote the following code. Its main advantage is doing the conversion without losing any data.

By the way, if you are okay with data loss, then wcstombs does the job.

#include <cstring>
#include <algorithm>
#include <tchar.h>

void lptstr2str(LPTSTR tch, char* &pch) // or (TCHAR* tch, char* &pch)
{
#ifndef UNICODE
    std::memcpy(pch, tch, strlen(tch) + 1);
#else
    size_t n =
        sizeof(TCHAR) / sizeof(char)* wcsnlen(tch, std::string::npos);
    pch = new char[n + 1];
    std::memcpy(pch, tch, n + 1);
    int len = n - std::count(pch, pch + n, NULL);
    std::remove(pch, pch + n, NULL);
    pch[len] = NULL;
#endif
}
久夏青 2024-07-17 00:16:59

我错过了一些简单的例子,所以这里是:(

对我来说 char* 与 char[] 相同)

LPCTSTR myLPCTSTR = getLPCTSTR();
TCHAR myT[500];
wcscpy(myT,myLPCTSTR);
char myC[500];
sprintf(myC, "%S", myT);

I was missing some simple example so here it is:

(for me char* is identical to char[])

LPCTSTR myLPCTSTR = getLPCTSTR();
TCHAR myT[500];
wcscpy(myT,myLPCTSTR);
char myC[500];
sprintf(myC, "%S", myT);
小嗲 2024-07-17 00:16:59

毫无疑问,许多人(例如,我们 unix 人)会对疯狂的 Microserf 双语感到恐惧 - “如果你的编译器处于 Unicode 模式,请使用 LPWSTR 或在其前面添加一个“T_”,但前提是它是静态的字符串,与“L”相同,或者如果使用 ATL,则使用 T2A(),但现在已经过时了;或者使用 VARIANT,但如果与 COM/OLE 链接则不使用”...)。

本页列出的“if (sizeof(TCHAR) == sizeof(char))”是对一个不错的解决方案的逻辑尝试,但它不会编译 - if-true 不会编译或 if-false 不会编译' 编译,具体取决于您的编译器标志(啊!)。
对于写后忘记的便携式解决方案,您需要求助于[过于通用的命名] UNICODE 宏。 我提供了对之前代码的修改:

string mfc_to_zstring (CString &sref)
{
    char nojoy[65536];
    char *ptr, *psin = NULL;
    string sot;
    LPCTSTR p = sref;


#if UNICODE
    if (sizeof(TCHAR) != sizeof(char))
    {
        size_t n = wcstombs(NULL, p, 0);
        if (n > 65530)
        {
            psin = new char[n + 1];
            wcstombs(psin, p, n + 1);
            ptr = psin;
        }
        else
        {
            wcstombs(nojoy, p, n + 1);
            ptr = nojoy;
        }

        sot = ptr;
        if (psin != NULL)
            delete psin;
    }
    else
        { std::cerr << "Aaargh! Microsoft horror.\n"; exit(1); }
#else
    if (sizeof(TCHAR) == sizeof(char))
    {
        const char *ptr = p;
        sot = ptr;
    }
    else
      { std::cerr << "Aaargh! You should never see this line\n"; exit(1); }
#endif

    return sot;
}

no doubt many (eg, us unix folk) will recoil in horror at the mad-hatter Microserf doublespeak - "if your compiler is in Unicode mode, use LPWSTR or stick a "T_" in front of it, but only if it's a static string, which is the same as an "L", or use T2A() if using ATL, but that's now outdated, or use VARIANT but not if linking with COM/OLE"...).

The "if (sizeof(TCHAR) == sizeof(char))" listed on this page is a logical attempt at a nice solution, but it won't compile - either the if-true won't compile or if-false wont' compile, depending on your compiler flags (Aaargh!).
For a write-and-forget portable solution you'll need to resort to the [too-generic named] UNICODE macro. I offer this adaptation of the previous code:

string mfc_to_zstring (CString &sref)
{
    char nojoy[65536];
    char *ptr, *psin = NULL;
    string sot;
    LPCTSTR p = sref;


#if UNICODE
    if (sizeof(TCHAR) != sizeof(char))
    {
        size_t n = wcstombs(NULL, p, 0);
        if (n > 65530)
        {
            psin = new char[n + 1];
            wcstombs(psin, p, n + 1);
            ptr = psin;
        }
        else
        {
            wcstombs(nojoy, p, n + 1);
            ptr = nojoy;
        }

        sot = ptr;
        if (psin != NULL)
            delete psin;
    }
    else
        { std::cerr << "Aaargh! Microsoft horror.\n"; exit(1); }
#else
    if (sizeof(TCHAR) == sizeof(char))
    {
        const char *ptr = p;
        sot = ptr;
    }
    else
      { std::cerr << "Aaargh! You should never see this line\n"; exit(1); }
#endif

    return sot;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文