如果涉及到托管和非托管的互调用,则数据的拆装封送将会很重要。.net提供了System.Runtime.InteropServices.Marshal来实现托管类型和非托管类型之间的拆装封送。对于字符串的封送是经常要用到的,本例中以一个代理类CharPtrProxy来避免手工对Marshal返回的IntPtr进行维护,非常方便安全。
平台:VS2005sp1 CLI
#pragma once
#include <string>
public ref class StringConvert
{
public:
template<typename T>
ref class CharPtrProxy
{
private:
System::IntPtr m_intPtr;
public:
CharPtrProxy(System::IntPtr intPtr)
{
m_intPtr = intPtr;
}
~CharPtrProxy()
{
System::Runtime::InteropServices::Marshal::FreeHGlobal(m_intPtr);
}
operator const T*()
{
return (const T*)m_intPtr.ToInt32();
}
};
public:
static CharPtrProxy<char>^ ToAsciiCharPtr(System::String^ str)
{
return gcnew CharPtrProxy<char>(System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(str));
}
static CharPtrProxy<wchar_t>^ ToUnicodeCharPtr(System::String^ str)
{
return gcnew CharPtrProxy<wchar_t>(System::Runtime::InteropServices::Marshal::StringToHGlobalUni(str));
}
static std::string ToStdString(System::String^ str)
{
return std::string(ToAsciiCharPtr(str));
}
static std::wstring ToStdWString(System::String^ str)
{
return std::wstring(ToUnicodeCharPtr(str));
}
};
评论