【问题标题】:Unicode project for CString to const byte*?CString 到 const byte* 的 Unicode 项目?
【发布时间】:2011-12-12 01:50:50
【问题描述】:

谁能帮我将 CString 转换为 const 字节指针。我尝试下面的代码,但它不起作用。我的程序使用 Unicode 设置。

Cstring hello = "MyApp";
const BYTE* pData = (const BYTE*)(LPCTSTR)hello;

谢谢。

【问题讨论】:

  • 您想要在本地代码页或其他内容中表示字符串的字节吗?

标签: c++ windows unicode


【解决方案1】:

来自How to convert CString to BYTE pointer

  • 将其解释为 ascii 字符串:

    CStringA asciiString( hello );
    const BYTE* lpData = (const BYTE*)(LPCSTR)asciiString;
    
  • 转换为代表本地代码页中字符串的字节:

    CT2CA buf( hello );
    const BYTE* lpData = (const BYTE*)buf;
    

【讨论】:

  • CString和CStringA有什么区别?
  • 谢谢它的工作。我使用第一个建议。但是知道为什么当我调用这个 RegSetValueEx(hKey,Path, NULL, REG_SZ, pData, sizeof(pData)); 时,它不会将“MyApp”写入注册表。
  • @Lufia:CStringCStringA 的区别与 _T("abc")"abc" 的区别相同,即 TCHAR 与 ANSI 字符串。 sizeof(pData)sizeof(pointer) 但您需要 pData 的字节长度(包括末尾的零字节)。
【解决方案2】:

【讨论】:

    【解决方案3】:

    对于初学者,您需要了解您是否使用 unicode。默认情况下,Visual Studio 喜欢制作应用程序,因此它们使用 Unicode。如果您想要的是 ANSI(每个字母仅使用 1 个字节),则需要将其从 Unicode 转换为 ANSI。这将为您提供对象的 BYTE*。这是一种方法:

        CString hello;
        hello=L"MyApp"; // Unicode string
    
    int iChars = WideCharToMultiByte( CP_UTF8,0,(LPCWSTR) hello,-1,NULL,0,NULL,NULL); // First we need to get the number of characters in the Unicode string
    if (iChars == 0) 
        return 0; // There are no characters here.
    
    BYTE* lpBuff = new BYTE[iChars];  // alocate the buffer with the number of characters found
        WideCharToMultiByte(CP_UTF8,0,(LPCWSTR) hello,-1,(LPSTR) lpBuff,iChars-1, NULL, NULL); // And convert the Unicode to ANSI, then put the result in our buffer.
    

    // 如果你想让它成为一个常量字节指针,只需添加这一行:

        const BYTE* cbOut = lpBuff;
    

    现在,如果您只想访问 CString 本身,那么只需将其转换为:

        const TCHAR* MyString = (LPCTSTR) hello;
    

    【讨论】:

      猜你喜欢
      • 2012-09-03
      • 1970-01-01
      • 2012-10-02
      • 2014-12-11
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      • 2013-02-28
      相关资源
      最近更新 更多