如何使用Unicode将CString转换为unsigned char *?

时间:2009-01-28 20:51:07

标签: visual-studio visual-studio-2008 visual-c++ string

我正在尝试做一些简单的事情。当我使用unicode字符集在Visual Studio 2008中执行以下代码时,xmlString是正确的。

不幸的是我需要将CString转换为unsigned char *。 使用下面的代码,ucStr变为“<” (即xmlString的第一个字符)。

我应该如何将CString转换为unsigned char *并保留所有信息?

        CString xmlString;
        xmlString.Format( _T("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><gateway><config-read><%s /></config-read></gateway>"), keyName);

        unsigned char * ucStr = reinterpret_cast<unsigned char *> (xmlString.GetBuffer());
        pgIRequest->SendXmlData( "dgv/gateway.xml", ucStr, xmlString.GetLength() + 1) ; 

5 个答案:

答案 0 :(得分:3)

我发现最简单的是使用CStringA构造函数,如下所示:

    CString xmlString;
    xmlString.Format( _T("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><gateway><config-read><%s /></config-read></gateway>"), "test");

    printf("%s\n",xmlString );  // fails "<"

    //unsigned char * ucStr = reinterpret_cast<unsigned char *> (xmlString.GetBuffer());

    CStringA ucStr( xmlString );

    printf("%s\n",ucStr );   // works!

答案 1 :(得分:3)

当'keyName'变量开始包含ISO-8859-1编码中无法表示的字符时,此代码段可能无效。为此,我建议使用UTF-8作为编码值创建一个字符串,使用CP_UTF8代码页使用WideCharToMultiByte转换为UTF-8字节流,并发送生成的utf8字节流。

答案 2 :(得分:1)

我认为您需要wcstombs,或者更确切地说,它需要更安全的wcstombs_s

答案 3 :(得分:0)

我假设“SendXmlData”需要字节数而不是字符数。

如果是这样,你想把“GetLength()+ 1”更改为“(GetLength()+ 1)* sizeof(xmlString [0])”。

答案 4 :(得分:0)

这是最终有效的代码:

CString xmlString;
        xmlString.Format( _T("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><gateway><config-read><%s /></config-read></gateway>"), keyName);
        CStringA ucStr( xmlString );
        unsigned char * ucStr2 = reinterpret_cast<unsigned char *> (ucStr.GetBuffer());
        pgIRequest->SendXmlData( "dgv/gateway.xml", ucStr2, xmlString.GetLength() + 1) ;// target on gateway to download