如何:將 System::String 轉換為 wchar_t* 或 char*

您可以在 Vcclr.h 中使用 PtrToStringChars ,將 轉換成 String 原生 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++ Interop (隱含 PInvoke)