Share via


방법: System::String을 wchar_t* 또는 char*로 변환

Vcclr.h에서 네이티브 wchar_t * 또는 char *.로 변환 String 하는 데 사용할 PtrToStringChars 수 있습니다. CLR 문자열은 내부적으로 유니코드이므로 항상 넓은 유니코드 문자열 포인터를 반환합니다. 그런 다음, 다음 예제와 같이 와이드에서 변환할 수 있습니다.

예시

// convert_string_to_wchar.cpp
// compile with: /clr
#include < stdio.h >
#include < stdlib.h >
#include < vcclr.h >

using namespace System;

int main() {
   String ^str = "Hello";

   // Pin memory so GC can't move it while native function is called
   pin_ptr<const wchar_t> wch = PtrToStringChars(str);
   printf_s("%S\n", wch);

   // Conversion to char* :
   // Can just convert wchar_t* to char* using one of the
   // conversion functions such as:
   // WideCharToMultiByte()
   // wcstombs_s()
   // ... etc
   size_t convertedChars = 0;
   size_t  sizeInBytes = ((str->Length + 1) * 2);
   errno_t err = 0;
   char    *ch = (char *)malloc(sizeInBytes);

   err = wcstombs_s(&convertedChars,
                    ch, sizeInBytes,
                    wch, sizeInBytes);
   if (err != 0)
      printf_s("wcstombs_s  failed!\n");

    printf_s("%s\n", ch);
}
Hello
Hello

참고 항목

C++ Interop 사용(암시적 PInvoke)