在.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::string 或 std::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