String^与string的相互转换
2015-12-09 13:58
197 查看
最近在做功率控制的实验时,需要对计算机的每个核的利用率进行计算和写出到文件。采用了c++调用c#dll的方法,在.net中string是需要用gcnew进行初始化,先来看看gcnew和普通的new的区别:
C++/CLI中使用gcnew关键字表示在托管堆上分配内存,并且为了与以前的指针区分,用^来替换*
,就语义上来说他们的区别大致如下:
1. gcnew返回的是一个句柄(Handle),而new返回的是实际的内存地址.
2. gcnew创建的对象由虚拟机托管,而new创建的对象必须自己来管理和释放.
暂时没有很深入的去理解这些区别。因为需要在c++的控制代码中对c#产生的String^变量进行写出,而默认的文件写出是string类型的,因此需要进行转换。查阅资料发现有人总结了一下较为简单的转换方式:
1:std::string转String^:
std::string stdstr="";
String^ str = marshal_as<String^>(stdstr);
2:String^转std::string:
String^ str= gcnew String();
std::string stdstr = marshal_as<std::string>(str->ToString());
3:CString转Sting^:
CString cstr="";
String^ str = marshal_as<String^>(cstr.GetBuffer());
cstr.ReleaseBuffer();
4:String^转CString:
String^ str;
CString cstr(str);
C++/CLI中使用gcnew关键字表示在托管堆上分配内存,并且为了与以前的指针区分,用^来替换*
,就语义上来说他们的区别大致如下:
1. gcnew返回的是一个句柄(Handle),而new返回的是实际的内存地址.
2. gcnew创建的对象由虚拟机托管,而new创建的对象必须自己来管理和释放.
暂时没有很深入的去理解这些区别。因为需要在c++的控制代码中对c#产生的String^变量进行写出,而默认的文件写出是string类型的,因此需要进行转换。查阅资料发现有人总结了一下较为简单的转换方式:
1:std::string转String^:
std::string stdstr="";
String^ str = marshal_as<String^>(stdstr);
2:String^转std::string:
String^ str= gcnew String();
std::string stdstr = marshal_as<std::string>(str->ToString());
3:CString转Sting^:
CString cstr="";
String^ str = marshal_as<String^>(cstr.GetBuffer());
cstr.ReleaseBuffer();
4:String^转CString:
String^ str;
CString cstr(str);
相关文章推荐
- 【LeetCode】 Largest Rectangle in Histogram O(n) 解法详析
- C# 关于方法中的参数(可选参数和命名参数)
- CSS中的数量查询
- 教学产品设计
- Visual Studio控制台程序输出窗口一闪而过的解决方法
- 时间如流水般逝去—兄弟连IT教育
- 编写iOS HTTP网络请求库(总)
- hdu 1060(取前n位)
- JAVA获取当前系统时间System.currentTimeMillis()
- 10014---Nginx 概述
- Swift第二天学习
- FAT32文件系统
- 跟我从零基础学习Unity3D开发--资源打包篇(AssetBundle)
- 打造H5动感影集的爱恨情仇–动画性能篇
- Java中的增补字符
- java多线程之模拟死锁
- 欢迎使用CSDN-markdown编辑器
- 补码
- ubuntu 14.04上源码编译安装php7
- Java代码中的字符编码转换