您好,很高兴为您解答。
可以在 Vcclr.h 中使用 PtrToStringChars 将 String 转换为本机 wchar_t * 或 char *。由于 CLR 字符串为内部 Unicode,因此这样通常会返回一个 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_ptrwch = 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
如若满意,请点击右侧【采纳答案】,如若还有问题,请点击【追问】
希望我的回答对您有所帮助,望采纳!
~ O(∩_∩)O~