几何尺寸与公差论坛------致力于产品几何量公差标准GD&T (GDT:ASME)|New GPS(ISO)研究/CAD设计/CAM加工/CMM测量

几何尺寸与公差论坛------致力于产品几何量公差标准GD&T (GDT:ASME)|New GPS(ISO)研究/CAD设计/CAM加工/CMM测量 (http://www.dimcax.com/hust/index.php)
-   vc编程 (http://www.dimcax.com/hust/forumdisplay.php?f=76)
-   -   将托管字符串System.String转换为char*或w_char*的函数PtrToStringChars (http://www.dimcax.com/hust/showthread.php?t=1146)

yogy 2007-07-23 02:06 PM

将托管字符串System.String转换为char*或w_char*的函数PtrToStringChars
 
将托管字符串System.String转换为char*或w_char*的函数PtrToStringChars

范例:
// 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);
}


所有的时间均为北京时间。 现在的时间是 08:02 PM.