.Net架构中String类型的转换

      在.Net架构中,经常有String^ path 这种类型的路径,而如opencv的保存函数imwrite()中,所使用的路径又是uchar* 类型。这两种类型的转换如下:
其中,curFileName是String ^类型的图片绝对路径,mat是已知的opencv图片,类型为Mat。

using namespace Runtime::InteropServices;
String^ shortName;
shortName = "E:/save/" + IO::Path::GetFileNameWithoutExtension(curFileName)+".bmp";
const char* charsShortName = (const char*)(Marshal::StringToHGlobalAnsi(shortName)).ToPointer();
imwrite(charsShortName ,mat);


   同理,在保存文字的时候,有时候也会需要这种转换,如下:

using namespace Runtime::InteropServices;
const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(curFileName)).ToPointer();
std::ofstream outfile("E:/out.txt",std::ios::app|std::ios::out);
outfile<<"字符为:"<<charsShortName<<std::endl;

 

下文转自http://msdn.microsoft.com/zh-cn/library/1b4az623(VS.80).aspx
 

可以在不使用 Vcclr.h 中的 PtrToStringChars 的情况下将 String 转换为 std::stringstd::wstring

示例

// convert_system_string.cpp
// compile with: /clr
#include <string>
#include <iostream>
using namespace std;
using namespace System;

void MarshalString ( String ^ s, string& os ) {
   using namespace Runtime::InteropServices;
   const char* chars = 
      (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}

void MarshalString ( String ^ s, wstring& os ) {
   using namespace Runtime::InteropServices;
   const wchar_t* chars = 
      (const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}

int main() {
   string a = "test";
   wstring b = L"test2";
   String ^ c = gcnew String("abcd");

   cout << a << endl;
   MarshalString(c, a);
   c = "efgh";
   MarshalString(c, b);
   cout << a << endl;
   wcout << b << endl;
}

结果:
test
abcd
efgh

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值