Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ CString到常量字节*的Unicode项目?_C++_Windows_Unicode - Fatal编程技术网

C++ CString到常量字节*的Unicode项目?

C++ CString到常量字节*的Unicode项目?,c++,windows,unicode,C++,Windows,Unicode,有人能帮我把CString转换成常量字节指针吗。我尝试下面的代码,但它不工作。我的程序使用Unicode设置 Cstring hello = "MyApp"; const BYTE* pData = (const BYTE*)(LPCTSTR)hello; 谢谢。试试(PCWSTR) 文件位于以下地址: 将其解释为ascii字符串: CStringA asciiString( hello ); const BYTE* lpData = (const BYTE*)(LPCSTR)asciiSt

有人能帮我把CString转换成常量字节指针吗。我尝试下面的代码,但它不工作。我的程序使用Unicode设置

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

试试(PCWSTR)

文件位于以下地址:

  • 将其解释为ascii字符串:

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

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

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

    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;

您想要在本地代码页中表示字符串的字节还是其他内容?CString和CStringA之间有什么不同?谢谢,它可以工作。我使用第一个建议。但是你知道为什么当我调用这个RegSetValueEx(hKey,Path,NULL,REG_SZ,pData,sizeof(pData))时;,它不会将“MyApp”写入注册表。@Lufia:CString
CString
vs
CStringA
的区别与
\u T(“abc”)
vs.
“abc”
的区别相同,即
TCHAR
vs.ANSI字符串
sizeof(pData)
sizeof(指针)
但您需要
pData的长度,以字节为单位(包括末尾的零字节)。