In Visual C ++. net, convert system: string * To char * or cstring.

Source: Internet
Author: User

This article describes how to convert a hosted Extension from system: string * To char * in Visual C ++. net.

Method 1

PtrtostringcharsSpecifies an internal pointer to the actual string object. If you pass this pointer to an unmanaged function call, you must first lock the pointer to ensure that the object will not be moved during asynchronous garbage collection:

//#include <vcclr.h>System::String * str = S"Hello world/n";const __wchar_t __pin * str1 = PtrToStringChars(str);wprintf(str1);

Method 2

StringtohglobalansiCopy the content of the hosted String object to the local heap and dynamically convert it to the ANSI format. This method will allocate the required local heap memory:

//using namespace System::Runtime::InteropServices;System::String * str = S"Hello world/n";char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);printf(str2);Marshal::FreeHGlobal(str2);

Method 3

Vc7CstringClass has a constructor that carries a hosted string pointer and loads its content to cstring:

//#include <atlstr.h>System::String * str = S"Hello world/n";CString str3(str); printf(str3);

Complete code example

//compiler option:cl /clr  #include <vcclr.h>#include <atlstr.h>#include <stdio.h>#using <mscorlib.dll>using namespace System;using namespace System::Runtime::InteropServices;int _tmain(void){System::String * str = S"Hello world/n";//method 1const __wchar_t __pin * str1 = PtrToStringChars(str);wprintf(str1);//method 2char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);printf(str2);Marshal::FreeHGlobal(str2);//method 3CString str3(str); printf(str3);return 0;}
Original address: http://support.microsoft.com /? Id = 311259

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.