System::String *,char*,string 等的类型转换 [转]

在VC 的编程中,常常会用到各类类型的转换,在MFC中textbox等控件获得的返回类型是System::String *,而写入的文件要求是 const char *类型的,下面介绍一些转换的方法:
string 转 CString    CString.format("%s", string.c_str());
编程

char* 转 CString    CString.format("%s", char*); 异步

char* 转 string       string change=new string s(char *); 函数

string 转 char *     char *p = string.c_str(); spa

CString转std::string CString str = dlg.GetPathName();
                           setlocale(LC_ALL, "chs");
                          char *p = new char[256];
                        wcstombs( p, str, 256 );
                         m_fileName = p;
指针

int 转CString而将数字转换为CString变量,code

                    能够使用CString的Format函数
                      CString s;  
                      int i = 64;  
                     s.Format("%d", i)  
     Format函数的功能很强,值得你研究一下。
orm

CString TO char *    对象

    要把CString转成char *,用操做符(LPCSTR内存

                               
CString转换 char[100]  
string

         char a[100];  
      CString str("aaaaaa");  
     strncpy(a,(LPCTSTR)str,sizeof(a));
CString类型的转换成int    

            CString aaa = "16" ;
       int int_chage = atoi((lpcstr)aaa) ;

char* 在装int     

          #include <stdlib.h>
          int atoi(const char *nptr);
           long atol(const char *nptr);
          long long atoll(const char *nptr);
          long long atoq(const char *nptr);

System::String 转化成 char *类型(网上提供有许多种类)

1 MSDN上的

#include < stdio.h >
#include < stdlib.h >
#include < vcclr.h >   
using namespace System;   
int main() {
String ^str = "Hello";   
        pin_ptr<const wchar_t> wch = PtrToStringChars(str);
printf_s("%S\n", wch);   
        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);
}

2 网上找的

PtrToStringChars 指定了一个指向实际 String 对象的内部指针。若是将此指针传递给非托管函数调用,则必须先锁定该指针,以确保在进行异步垃圾回收过程当中对象不会移动:

//#include <vcclr.h> System::String * str = S"Hello world\n"; const __wchar_t __pin * str1 = PtrToStringChars(str); wprintf(str1);
3 感受这种最好用的

StringToHGlobalAnsi 将托管 String 对象的内容复制到本机堆,

而后动态地将它转换为美国国家标准学会 (ANSI) 格式。

此方法将分配所需的本机堆内存:

using namespace System;

using namespace System::Runtime::InteropServices; System::String * str = S"Hello world\n"; char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str); printf(str2);
相关文章
相关标签/搜索