Share via


如何:将 System::String 转换为 wchar_t* 或 char*

可以在 Vcclr.h 中使用 PtrToStringCharsString 转换为本机 wchar_t *char *。 这将始终返回宽 Unicode 字符串指针,因为 CLR 字符串在内部为 Unicode。 然后,可以从宽字符串进行转换,如以下示例所示。

示例

// 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++ 互操作(隐式 PInvoke)