방법: 다양한 문자열 형식 간 변환

이 문서에서는 다양한 Visual C++ 문자열 형식을 다른 문자열로 변환하는 방법을 보여 줍니다.

포함char *되는 문자열 형식에는 , , _bstr_twchar_t*, basic_stringCComBSTRCString및 .System.String

모든 경우에 문자열의 복사본은 새 형식으로 변환할 때 만들어집니다. 새 문자열을 변경해도 원래 문자열에는 영향을 주지 않으며 그 반대의 경우도 마찬가지입니다.

좁은 문자열과 와이드 문자열을 변환하는 방법에 대한 자세한 배경 정보는 좁은 문자열과 와이드 문자열 간 변환을 참조 하세요.

예제 실행

Visual Studio 2022에서 예제를 실행하려면 새 C++ Windows 콘솔 앱을 만들 수 있습니다. 또는 C++/CLI 지원을 설치한 경우 CLR 콘솔 앱(.NET Framework)을 만들 수 있습니다.

CLR 콘솔 앱을 만드는 경우 컴파일러 및 디버거 설정을 다음과 같이 변경할 필요가 없습니다. 그러나 각 예제의 맨 위에 추가 #include "pch.h" 해야 합니다.

어느 쪽이든 프로젝트 속성>링커>입력>추가 종속성에 추가 comsuppw.lib합니다.

예제를 실행하는 새 C++ Windows 콘솔 앱을 만드는 경우 다음 프로젝트를 변경합니다.

  • /clr 프로젝트 속성>C++>명령줄 추가 옵션에 명령줄 인수와 /Zc:twoPhase- 명령줄>인수를 추가합니다.

스위치는 /clr C++ Windows 콘솔 앱 프로젝트를 만들 때 설정된 일부 컴파일러 스위치와 충돌합니다. 다음 링크는 IDE에서 충돌하는 스위치를 끌 수 있는 위치에 대한 지침을 제공합니다.

예: 다음에서 변환 char *

설명

이 예제에서는 위에 나열된 문자열 형식으로 char * 변환하는 방법을 보여 줍니다. char * 문자열(C 스타일 문자열이라고도 함)은 종료 null을 사용하여 문자열의 끝을 나타냅니다. C 스타일 문자열은 일반적으로 문자당 1바이트가 필요하지만 2바이트를 사용할 수도 있습니다. 아래 char * 예제에서는 와이드 유니코드 문자열에서 변환된 문자열 데이터 때문에 문자열을 멀티바이트 문자열이라고도 합니다. 단일 바이트 및 멀티바이트 문자(MBCS) 함수는 문자열에서 char * 작동할 수 있습니다.

이 예제를 실행하고 디버깅하는 방법에 대한 자세한 내용은 예제 실행을 참조 하세요.

코드

// convert_from_char.cpp
// compile with: /clr /Zc:twoPhase- /link comsuppw.lib

#include <iostream>
#include <stdlib.h>
#include <string>

#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"

using namespace std;
using namespace System;

int main()
{
    // Create and display a C-style string, and then use it
    // to create different kinds of strings.
    const char* orig = "Hello, World!";
    cout << orig << " (char *)" << endl;

    // newsize describes the length of the
    // wchar_t string called wcstring in terms of the number
    // of wide characters, not the number of bytes.
    size_t newsize = strlen(orig) + 1;

    // The following creates a buffer large enough to contain
    // the exact number of characters in the original string
    // in the new format. If you want to add more characters
    // to the end of the string, increase the value of newsize
    // to increase the size of the buffer.
    wchar_t* wcstring = new wchar_t[newsize];

    // Convert char* string to a wchar_t* string.
    size_t convertedChars = 0;
    mbstowcs_s(&convertedChars, wcstring, newsize, orig, _TRUNCATE);
    // Display the result and indicate the type of string that it is.
    wcout << wcstring << L" (wchar_t *)" << endl;
    delete []wcstring;

    // Convert the C-style string to a _bstr_t string.
    _bstr_t bstrt(orig);
    // Append the type of string to the new string
    // and then display the result.
    bstrt += " (_bstr_t)";
    cout << bstrt << endl;

    // Convert the C-style string to a CComBSTR string.
    CComBSTR ccombstr(orig);
    if (ccombstr.Append(L" (CComBSTR)") == S_OK)
    {
        CW2A printstr(ccombstr);
        cout << printstr << endl;
    }

    // Convert the C-style string to a CStringA and display it.
    CStringA cstringa(orig);
    cstringa += " (CStringA)";
    cout << cstringa << endl;

    // Convert the C-style string to a CStringW and display it.
    CStringW cstring(orig);
    cstring += " (CStringW)";
    // To display a CStringW correctly, use wcout and cast cstring
    // to (LPCTSTR).
    wcout << (LPCTSTR)cstring << endl;

    // Convert the C-style string to a basic_string and display it.
    string basicstring(orig);
    basicstring += " (basic_string)";
    cout << basicstring << endl;

    // Convert the C-style string to a System::String and display it.
    String^ systemstring = gcnew String(orig);
    systemstring += " (System::String)";
    Console::WriteLine("{0}", systemstring);
    delete systemstring;
}
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (_bstr_t)
Hello, World! (CComBSTR)
Hello, World! (CStringA)
Hello, World! (CStringW)
Hello, World! (basic_string)
Hello, World! (System::String)

예: 다음에서 변환 wchar_t *

설명

이 예제에서는 다른 문자열 형식으로 wchar_t * 변환하는 방법을 보여 줍니다. 여러 문자열 형식(예: wchar_t *와이드 문자 형식)을 구현합니다. 멀티바이트와 와이드 문자 형식 간에 문자열을 변환하려면 같은 클래스에 대해 단일 함수 호출 mbstowcs_s 또는 생성자 호출을 CStringA사용할 수 있습니다.

이 예제를 실행하고 디버깅하는 방법에 대한 자세한 내용은 예제 실행을 참조 하세요.

코드

// convert_from_wchar_t.cpp
// compile with: /clr /Zc:twoPhase- /link comsuppw.lib

#include <iostream>
#include <stdlib.h>
#include <string>

#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"

using namespace std;
using namespace System;

int main()
{
    // Create a string of wide characters, display it, and then
    // use this string to create other types of strings.
    const wchar_t* orig = L"Hello, World!";
    wcout << orig << L" (wchar_t *)" << endl;

    // Convert the wchar_t string to a char* string. Record
    // the length of the original string and add 1 to it to
    // account for the terminating null character.
    size_t origsize = wcslen(orig) + 1;
    size_t convertedChars = 0;

    // Use a multibyte string to append the type of string
    // to the new string before displaying the result.
    char strConcat[] = " (char *)";
    size_t strConcatsize = (strlen(strConcat) + 1) * 2;

    // Allocate two bytes in the multibyte output string for every wide
    // character in the input string (including a wide character
    // null). Because a multibyte character can be one or two bytes,
    // you should allot two bytes for each character. Having extra
    // space for the new string isn't an error, but having
    // insufficient space is a potential security problem.
    const size_t newsize = origsize * 2;
    // The new string will contain a converted copy of the original
    // string plus the type of string appended to it.
    char* nstring = new char[newsize + strConcatsize];

    // Put a copy of the converted string into nstring
    wcstombs_s(&convertedChars, nstring, newsize, orig, _TRUNCATE);
    // append the type of string to the new string.
    _mbscat_s((unsigned char*)nstring, newsize + strConcatsize, (unsigned char*)strConcat);
    // Display the result.
    cout << nstring << endl;
    delete []nstring;

    // Convert a wchar_t to a _bstr_t string and display it.
    _bstr_t bstrt(orig);
    bstrt += " (_bstr_t)";
    cout << bstrt << endl;

    // Convert the wchar_t string to a BSTR wide character string
    // by using the ATL CComBSTR wrapper class for BSTR strings.
    // Then display the result.

    CComBSTR ccombstr(orig);
    if (ccombstr.Append(L" (CComBSTR)") == S_OK)
    {
        // CW2A converts the string in ccombstr to a multibyte
        // string in printstr, used here for display output.
        CW2A printstr(ccombstr);
        cout << printstr << endl;
        // The following line of code is an easier way to
        // display wide character strings:
        wcout << (LPCTSTR)ccombstr << endl;
    }

    // Convert a wide wchar_t string to a multibyte CStringA,
    // append the type of string to it, and display the result.
    CStringA cstringa(orig);
    cstringa += " (CStringA)";
    cout << cstringa << endl;

    // Convert a wide character wchar_t string to a wide
    // character CStringW string and append the type of string to it
    CStringW cstring(orig);
    cstring += " (CStringW)";
    // To display a CStringW correctly, use wcout and cast cstring
    // to (LPCTSTR).
    wcout << (LPCTSTR)cstring << endl;

    // Convert the wide character wchar_t string to a
    // basic_string, append the type of string to it, and
    // display the result.
    wstring basicstring(orig);
    basicstring += L" (basic_string)";
    wcout << basicstring << endl;

    // Convert a wide character wchar_t string to a
    // System::String string, append the type of string to it,
    // and display the result.
    String^ systemstring = gcnew String(orig);
    systemstring += " (System::String)";
    Console::WriteLine("{0}", systemstring);
    delete systemstring;
}
Hello, World! (wchar_t *)
Hello, World! (char *)
Hello, World! (_bstr_t)
Hello, World! (CComBSTR)
Hello, World! (CStringA)
Hello, World! (CStringW)
Hello, World! (basic_string)
Hello, World! (System::String)

예: 다음에서 변환 _bstr_t

설명

이 예제에서는 다른 문자열 형식으로 _bstr_t 변환하는 방법을 보여 줍니다. 개체는 _bstr_t 와이드 문자열 BSTR 을 캡슐화합니다. 문자열에는 BSTR 길이 값이 있고 null 문자를 사용하여 문자열을 종료하지 않지만 변환하는 문자열 형식에는 종료 null 문자가 필요할 수 있습니다.

이 예제를 실행하고 디버깅하는 방법에 대한 자세한 내용은 예제 실행을 참조 하세요.

코드

// convert_from_bstr_t.cpp
// compile with: /clr /Zc:twoPhase- /link comsuppw.lib

#include <iostream>
#include <stdlib.h>
#include <string>

#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"

using namespace std;
using namespace System;

int main()
{
    // Create a _bstr_t string, display the result, and indicate the
    // type of string that it is.
    _bstr_t orig("Hello, World!");
    wcout << orig << " (_bstr_t)" << endl;

    // Convert the wide character _bstr_t string to a C-style
    // string. To be safe, allocate two bytes for each character
    // in the char* string, including the terminating null.
    const size_t newsize = (orig.length() + 1) * 2;
    char* nstring = new char[newsize];

    // Uses the _bstr_t operator (char *) to obtain a null
    // terminated string from the _bstr_t object for
    // nstring.
    strcpy_s(nstring, newsize, (char*)orig);
    strcat_s(nstring, newsize, " (char *)");
    cout << nstring << endl;
    delete []nstring;

    // Prepare the type of string to append to the result.
    wchar_t strConcat[] = L" (wchar_t *)";
    size_t strConcatLen = wcslen(strConcat) + 1;

    // Convert a _bstr_t to a wchar_t* string.
    const size_t widesize = orig.length() + strConcatLen;
    wchar_t* wcstring = new wchar_t[newsize];
    wcscpy_s(wcstring, widesize, (wchar_t*)orig);
    wcscat_s(wcstring, widesize, strConcat);
    wcout << wcstring << endl;
    delete []wcstring;

    // Convert a _bstr_t string to a CComBSTR string.
    CComBSTR ccombstr((char*)orig);
    if (ccombstr.Append(L" (CComBSTR)") == S_OK)
    {
        CW2A printstr(ccombstr);
        cout << printstr << endl;
    }

    // Convert a _bstr_t to a CStringA string.
    CStringA cstringa(orig.GetBSTR());
    cstringa += " (CStringA)";
    cout << cstringa << endl;

    // Convert a _bstr_t to a CStringW string.
    CStringW cstring(orig.GetBSTR());
    cstring += " (CStringW)";
    // To display a cstring correctly, use wcout and
    // "cast" the cstring to (LPCTSTR).
    wcout << (LPCTSTR)cstring << endl;

    // Convert the _bstr_t to a basic_string.
    string basicstring((char*)orig);
    basicstring += " (basic_string)";
    cout << basicstring << endl;

    // Convert the _bstr_t to a System::String.
    String^ systemstring = gcnew String((char*)orig);
    systemstring += " (System::String)";
    Console::WriteLine("{0}", systemstring);
    delete systemstring;
}
Hello, World! (_bstr_t)
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (CComBSTR)
Hello, World! (CStringA)
Hello, World! (CStringW)
Hello, World! (basic_string)
Hello, World! (System::String)

예: 다음에서 변환 CComBSTR

설명

이 예제에서는 다른 문자열 형식으로 CComBSTR 변환하는 방법을 보여 줍니다. 마찬가지로 _bstr_t개체는 CComBSTR 와이드 문자열 BSTR 을 캡슐화합니다. 문자열에는 BSTR 길이 값이 있고 null 문자를 사용하여 문자열을 종료하지 않지만 변환하는 문자열 형식에는 종료 null이 필요할 수 있습니다.

이 예제를 실행하고 디버깅하는 방법에 대한 자세한 내용은 예제 실행을 참조 하세요.

코드

// convert_from_ccombstr.cpp
// compile with: /clr /Zc:twoPhase- /link comsuppw.lib

#include <iostream>
#include <stdlib.h>
#include <string>

#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"
#include "vcclr.h"

using namespace std;
using namespace System;
using namespace System::Runtime::InteropServices;

int main()
{
    // Create and initialize a BSTR string by using a CComBSTR object.
    CComBSTR orig("Hello, World!");
    // Convert the BSTR into a multibyte string, display the result,
    // and indicate the type of string that it is.
    CW2A printstr(orig);
    cout << printstr << " (CComBSTR)" << endl;

    // Convert a wide character CComBSTR string to a
    // regular multibyte char* string. Allocate enough space
    // in the new string for the largest possible result,
    // including space for a terminating null.
    const size_t newsize = (orig.Length() + 1) * 2;
    char* nstring = new char[newsize];

    // Create a string conversion object, copy the result to
    // the new char* string, and display the result.
    CW2A tmpstr1(orig);
    strcpy_s(nstring, newsize, tmpstr1);
    cout << nstring << " (char *)" << endl;
    delete []nstring;

    // Prepare the type of string to append to the result.
    wchar_t strConcat[] = L" (wchar_t *)";
    size_t strConcatLen = wcslen(strConcat) + 1;

    // Convert a wide character CComBSTR string to a wchar_t*.
    // The code first determines the length of the converted string
    // plus the length of the appended type of string, then
    // prepares the final wchar_t string for display.
    const size_t widesize = orig.Length() + strConcatLen;
    wchar_t* wcstring = new wchar_t[widesize];
    wcscpy_s(wcstring, widesize, orig);
    wcscat_s(wcstring, widesize, strConcat);

    // Display the result. Unlike CStringW, a wchar_t doesn't need
    // a cast to (LPCTSTR) with wcout.
    wcout << wcstring << endl;
    delete []wcstring;

    // Convert a wide character CComBSTR to a wide character _bstr_t,
    // append the type of string to it, and display the result.
    _bstr_t bstrt(orig);
    bstrt += " (_bstr_t)";
    cout << bstrt << endl;

    // Convert a wide character CComBSTR to a multibyte CStringA,
    // append the type of string to it, and display the result.
    CStringA cstringa(orig);
    cstringa += " (CStringA)";
    cout << cstringa << endl;

    // Convert a wide character CComBSTR to a wide character CStringW.
    CStringW cstring(orig);
    cstring += " (CStringW)";
    // To display a cstring correctly, use wcout and cast cstring
    // to (LPCTSTR).
    wcout << (LPCTSTR)cstring << endl;

    // Convert a wide character CComBSTR to a wide character
    // basic_string.
    wstring basicstring(orig);
    basicstring += L" (basic_string)";
    wcout << basicstring << endl;

    // Convert a wide character CComBSTR to a System::String.
    String^ systemstring = gcnew String(orig);
    systemstring += " (System::String)";
    Console::WriteLine("{0}", systemstring);
    delete systemstring;
}
Hello, World! (CComBSTR)
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (_bstr_t)
Hello, World! (CStringA)
Hello, World! (CStringW)
Hello, World! (basic_string)
Hello, World! (System::String)

예: 다음에서 변환 CString

설명

이 예제에서는 다른 문자열 형식으로 CString 변환하는 방법을 보여 줍니다. CString 는 데이터 형식을 TCHAR 기반으로 하며, 기호가 정의되었는지 여부에 _UNICODE 따라 달라집니다. 정의 TCHAR 되지 않은 경우 _UNICODE 멀티바이트 문자열로 char 정의되고 CString 멀티바이트 문자열을 포함합니다. 정의된 TCHAR 경우 _UNICODE 와이드 문자열로 wchar_t 정의되고 CString 와이드 문자열을 포함합니다.

CStringA 는 형식을 char 포함하고 싱글바이트 또는 멀티바이트 문자열을 지원합니다. CStringW 는 와이드 문자 버전입니다. CStringA 컴파일 CStringW 하는 방법을 결정하는 데는 사용하지 _UNICODE 마세요. CStringACStringW 는 버퍼 크기 할당 및 출력 처리의 사소한 차이를 명확히 하기 위해 이 예제에서 사용됩니다.

이 예제를 실행하고 디버깅하는 방법에 대한 자세한 내용은 예제 실행을 참조 하세요.

코드

// convert_from_cstring.cpp
// compile with: /clr /Zc:twoPhase- /link comsuppw.lib

#include <iostream>
#include <stdlib.h>
#include <string>

#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"

using namespace std;
using namespace System;

int main()
{
    // Set up a multibyte CStringA string.
    CStringA origa("Hello, World!");
    cout << origa << " (CStringA)" << endl;

    // Set up a wide character CStringW string.
    CStringW origw("Hello, World!");
    wcout << (LPCTSTR)origw << L" (CStringW)" << endl;

    // Convert to a char* string from CStringA string
    // and display the result.
    const size_t newsizea = origa.GetLength() + 1;
    char* nstringa = new char[newsizea];
    strcpy_s(nstringa, newsizea, origa);
    cout << nstringa << " (char *)" << endl;
    delete []nstringa;

    // Convert to a char* string from a wide character
    // CStringW string. To be safe, we allocate two bytes for each
    // character in the original string, including the terminating
    // null.
    const size_t newsizew = (origw.GetLength() + 1) * 2;
    char* nstringw = new char[newsizew];
    size_t convertedCharsw = 0;
    wcstombs_s(&convertedCharsw, nstringw, newsizew, origw, _TRUNCATE);
    cout << nstringw << " (char *)" << endl;
    delete []nstringw;

    // Convert to a wchar_t* from CStringA
    size_t convertedCharsa = 0;
    wchar_t* wcstring = new wchar_t[newsizea];
    mbstowcs_s(&convertedCharsa, wcstring, newsizea, origa, _TRUNCATE);
    wcout << wcstring << L" (wchar_t *)" << endl;
    delete []wcstring;

    // Convert to a wide character wchar_t* string from
    // a wide character CStringW string.
    wchar_t* n2stringw = new wchar_t[newsizew];
    wcscpy_s(n2stringw, newsizew, origw);
    wcout << n2stringw << L" (wchar_t *)" << endl;
    delete []n2stringw;

    // Convert to a wide character _bstr_t string from
    // a multibyte CStringA string.
    _bstr_t bstrt(origa);
    bstrt += L" (_bstr_t)";
    wcout << bstrt << endl;

    // Convert to a wide character _bstr_t string from
    // a wide character CStringW string.
    bstr_t bstrtw(origw);
    bstrtw += " (_bstr_t)";
    wcout << bstrtw << endl;

    // Convert to a wide character CComBSTR string from
    // a multibyte character CStringA string.
    CComBSTR ccombstr(origa);
    if (ccombstr.Append(L" (CComBSTR)") == S_OK)
    {
        // Convert the wide character string to multibyte
        // for printing.
        CW2A printstr(ccombstr);
        cout << printstr << endl;
    }

    // Convert to a wide character CComBSTR string from
    // a wide character CStringW string.
    CComBSTR ccombstrw(origw);

    // Append the type of string to it, and display the result.
    if (ccombstrw.Append(L" (CComBSTR)") == S_OK)
    {
        CW2A printstrw(ccombstrw);
        wcout << printstrw << endl;
    }

    // Convert a multibyte character CStringA to a
    // multibyte version of a basic_string string.
    string basicstring(origa);
    basicstring += " (basic_string)";
    cout << basicstring << endl;

    // Convert a wide character CStringW to a
    // wide character version of a basic_string
    // string.
    wstring basicstringw(origw);
    basicstringw += L" (basic_string)";
    wcout << basicstringw << endl;

    // Convert a multibyte character CStringA to a
    // System::String.
    String^ systemstring = gcnew String(origa);
    systemstring += " (System::String)";
    Console::WriteLine("{0}", systemstring);
    delete systemstring;

    // Convert a wide character CStringW to a
    // System::String.
    String^ systemstringw = gcnew String(origw);
    systemstringw += " (System::String)";
    Console::WriteLine("{0}", systemstringw);
    delete systemstringw;
}
Hello, World! (CStringA)
Hello, World! (CStringW)
Hello, World! (char *)
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (wchar_t *)
Hello, World! (_bstr_t)
Hello, World! (_bstr_t)
Hello, World! (CComBSTR)
Hello, World! (CComBSTR)
Hello, World! (basic_string)
Hello, World! (System::String)

예: 다음에서 변환 basic_string

설명

이 예제에서는 다른 문자열 형식으로 basic_string 변환하는 방법을 보여 줍니다.

이 예제를 실행하고 디버깅하는 방법에 대한 자세한 내용은 예제 실행을 참조 하세요.

코드

// convert_from_basic_string.cpp
// compile with: /clr /Zc:twoPhase- /link comsuppw.lib

#include <iostream>
#include <stdlib.h>
#include <string>

#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"

using namespace std;
using namespace System;

int main()
{
    // Set up a basic_string string.
    string orig("Hello, World!");
    cout << orig << " (basic_string)" << endl;

    // Convert a wide character basic_string string to a multibyte char*
    // string. To be safe, we allocate two bytes for each character
    // in the original string, including the terminating null.
    const size_t newsize = (orig.size() + 1) * 2;

    char* nstring = new char[newsize];
    strcpy_s(nstring, newsize, orig.c_str());
    cout << nstring << " (char *)" << endl;
    delete []nstring;

    // Convert a basic_string string to a wide character
    // wchar_t* string. You must first convert to a char*
    // for this to work.
    const size_t newsizew = orig.size() + 1;
    size_t convertedChars = 0;
    wchar_t* wcstring = new wchar_t[newsizew];
    mbstowcs_s(&convertedChars, wcstring, newsizew, orig.c_str(), _TRUNCATE);
    wcout << wcstring << L" (wchar_t *)" << endl;
    delete []wcstring;

    // Convert a basic_string string to a wide character
    // _bstr_t string.
    _bstr_t bstrt(orig.c_str());
    bstrt += L" (_bstr_t)";
    wcout << bstrt << endl;

    // Convert a basic_string string to a wide character
    // CComBSTR string.
    CComBSTR ccombstr(orig.c_str());
    if (ccombstr.Append(L" (CComBSTR)") == S_OK)
    {
        // Make a multibyte version of the CComBSTR string
        // and display the result.
        CW2A printstr(ccombstr);
        cout << printstr << endl;
    }

    // Convert a basic_string string into a multibyte
    // CStringA string.
    CStringA cstring(orig.c_str());
    cstring += " (CStringA)";
    cout << cstring << endl;

    // Convert a basic_string string into a wide
    // character CStringW string.
    CStringW cstringw(orig.c_str());
    cstringw += L" (CStringW)";
    wcout << (LPCTSTR)cstringw << endl;

    // Convert a basic_string string to a System::String
    String^ systemstring = gcnew String(orig.c_str());
    systemstring += " (System::String)";
    Console::WriteLine("{0}", systemstring);
    delete systemstring;
}
Hello, World! (basic_string)
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (_bstr_t)
Hello, World! (CComBSTR)
Hello, World! (CStringA)
Hello, World! (CStringW)
Hello, World! (System::String)

예: 다음에서 변환 System::String

설명

이 예제에서는 와이드 문자 System::String 에서 다른 문자열 형식으로 변환하는 방법을 보여 줍니다.

이 예제를 실행하고 디버깅하는 방법에 대한 자세한 내용은 예제 실행을 참조 하세요.

코드

// convert_from_system_string.cpp
// compile with: /clr /Zc:twoPhase- /link comsuppw.lib

#include <iostream>
#include <stdlib.h>
#include <string>

#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"
#include "vcclr.h"

using namespace std;
using namespace System;
using namespace System::Runtime::InteropServices;

int main()
{
    // Set up a System::String and display the result.
    String^ orig = gcnew String("Hello, World!");
    Console::WriteLine("{0} (System::String)", orig);

    // Obtain a pointer to the System::String in order to
    // first lock memory into place, so that the
    // Garbage Collector (GC) cannot move that object
    // while we call native functions.
    pin_ptr<const wchar_t> wch = PtrToStringChars(orig);

    // Make a copy of the System::String as a multibyte
    // char* string. Allocate two bytes in the multibyte
    // output string for every wide character in the input
    // string, including space for a terminating null.
    size_t origsize = wcslen(wch) + 1;
    const size_t newsize = origsize * 2;
    size_t convertedChars = 0;
    char* nstring = new char[newsize];
    wcstombs_s(&convertedChars, nstring, newsize, wch, _TRUNCATE);
    cout << nstring << " (char *)" << endl;
    delete []nstring;

    // Convert a wide character System::String to a
    // wide character wchar_t* string.
    const size_t newsizew = origsize;
    wchar_t* wcstring = new wchar_t[newsizew];
    wcscpy_s(wcstring, newsizew, wch);
    wcout << wcstring << L" (wchar_t *)" << endl;
    delete []wcstring;

    // Convert a wide character System::String to a
    // wide character _bstr_t string.
    _bstr_t bstrt(wch);
    bstrt += " (_bstr_t)";
    cout << bstrt << endl;

    // Convert a wide character System::String
    // to a wide character CComBSTR string.
    CComBSTR ccombstr(wch);
    if (ccombstr.Append(L" (CComBSTR)") == S_OK)
    {
        // Make a multibyte copy of the CComBSTR string
        // and display the result.
        CW2A printstr(ccombstr);
        cout << printstr << endl;
    }

    // Convert a wide character System::String to
    // a multibyte CStringA string.
    CStringA cstring(wch);
    cstring += " (CStringA)";
    cout << cstring << endl;

    // Convert a wide character System::String to
    // a wide character CStringW string.
    CStringW cstringw(wch);
    cstringw += " (CStringW)";
    wcout << (LPCTSTR)cstringw << endl;

    // Convert a wide character System::String to
    // a wide character basic_string.
    wstring basicstring(wch);
    basicstring += L" (basic_string)";
    wcout << basicstring << endl;

    delete orig;
}
Hello, World! (System::String)
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (_bstr_t)
Hello, World! (CComBSTR)
Hello, World! (CStringA)
Hello, World! (CStringW)
Hello, World! (basic_string)

좁은 문자열과 와이드 문자열 간 변환

레거시 C 및 Windows 앱은 좁은 문자열과 와이드 문자열을 처리할 때 유니코드 인코딩 대신 코드 페이지를 사용합니다.

.NET 문자열은 UTF-16이지만 ATL은 CStringA 좁은 문자열이며 Win32 함수에서 와이드에서 좁은 문자열로 변환합니다 WideCharToMultiByte . C 스타일 CHAR* (C 스타일 CHAR* 은 .NET byte*)을 문자열로 변환할 때 반대되는 Win32 함수 MultiByteToWideChar 가 호출됩니다.

두 함수 모두 코드 페이지의 Windows 개념을 사용합니다. 문화권의 .NET 개념이 아닙니다. 시스템 코드 페이지를 변경하려면 검색 상자 >영역(날짜, 시간 또는 숫자 형식 변경)>관리>제>도 변경 로캘에 입력 Region 할 제어판 사용하여 지역 설정을 사용합니다.

en-US Windows의 언어 버전에서 코드 페이지는 기본적으로 1033으로 설정됩니다. Windows의 다른 언어를 설치하는 경우 다른 코드 페이지가 있습니다. 제어판을 사용하여 변경할 수 있습니다.

넓고 좁은 변환을 수행하는 방식 CStringA 과 좁은 변환에서 와이드 변환을 수행하는 방식이 gcnew string(CHAR*) 일치하지 않습니다. CStringACP_THREAD_ACP현재 스레드 코드 페이지를 사용하여 축소 변환 메서드로 전달합니다. 그러나 string.ctor(sbyte*) 현재 시스템 코드 페이지를 사용하는 것을 의미하는 확대 변환 메서드에 전달CP_ACP합니다. 시스템 및 스레드 코드 페이지가 일치하지 않으면 왕복 데이터 손상이 발생할 수 있습니다.

이 차이를 조정하려면 상수 _CONVERSION_DONT_USE_THREAD_LOCALE)를 사용하여 대신 사용할 CP_ACP 변환(예: .NET) CP_THREAD_ACP을 가져옵니다. 자세한 내용은 _CONVERSION_DONT_USE_THREAD_LOCALE를 참조하세요.

또 다른 방법은 호출GetThreadLocale하는 데 사용하는 pinvoke 것입니다. 반환 LCID 된 값을 CultureInfo사용하여 . 그런 다음 변환에 사용할 코드 페이지를 가져오는 데 사용합니다 CultureInfo.TextInfo .

참고 항목

ATL 및 MFC 문자열 변환 매크로
CString C 스타일 문자열과 관련된 작업
방법: 표준 String 변환 System::String
방법: 표준으로 변환 System::StringString
방법: 변환 System::String 방법 wchar_t* 또는 char*
다음을 사용하여 프로그래밍 CComBSTR
mbstowcs_s, _mbstowcs_s_l
wcstombs_s, _wcstombs_s_l
strcpy_s, wcscpy_s, _mbscpy_s
strcat_s, wcscat_s, _mbscat_s
pin_ptr (C++/CLI)