C++ 如何创建指向托管字符串的共享指针?

C++ 如何创建指向托管字符串的共享指针?,c++,stl,visual-studio-2012,C++,Stl,Visual Studio 2012,我想对托管字符串使用共享指针,但我无法理解语法。要创建共享指针,我需要一个分配器来调用Marshal::StringToHGlobalAnsi(managedString)。要释放指针,自定义删除程序应该调用marshall::FreeHGlobal。我要找的东西是: std::shared_ptr<IntPtr> managedFilename(Marshal::StringToHGlobalAnsi(videoFilename), Marshal::FreeHGloba

我想对托管字符串使用共享指针,但我无法理解语法。要创建共享指针,我需要一个分配器来调用
Marshal::StringToHGlobalAnsi(managedString)
。要释放指针,自定义删除程序应该调用
marshall::FreeHGlobal
。我要找的东西是:

std::shared_ptr<IntPtr> managedFilename(Marshal::StringToHGlobalAnsi(videoFilename), 
    Marshal::FreeHGlobal);  // does not compile
std::shared\ptr managedFilename(封送:StringToHGlobalAnsi(视频文件名),
封送员:FreeHGlobal);//不编译
编译器被
videoFilename
参数和
IntPtr
无效转换阻塞


我在传统的C语言中工作;但是,我想使用STL。

您希望获得什么样的结果

如果要在非托管代码中使用字符串,必须编写如下代码

void MarshalString ( String ^ s, std::string& os ) {
    using namespace Runtime::InteropServices;
    const char* chars = 
    (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
    os = chars;
    Marshal::FreeHGlobal(IntPtr((void*)chars));
}
如果您正在编写托管代码,请直接使用字符串^type

shared_ptr不适用于托管类型

UPD 你可以这样做,但为什么

static void MyFreeHGlobal(void * ptr)
{
    using namespace Runtime::InteropServices;
    Marshal::FreeHGlobal(System::IntPtr(ptr));
}

// ...
System::String ^ s = L"test";
using namespace Runtime::InteropServices;
boost::shared_ptr<void> managedFilename(Marshal::StringToHGlobalAnsi(s).ToPointer(), 
    &MyFreeHGlobal); 
静态void MyFreeHGlobal(void*ptr)
{
使用命名空间运行时::InteropServices;
Marshal::FreeHGlobal(系统::IntPtr(ptr));
}
// ...
系统::字符串^s=L“测试”;
使用命名空间运行时::InteropServices;
boost::shared_ptr managedFilename(封送处理::StringToHGlobalAnsi.ToPointer(),
&MyFreeHGlobal);

我正在将托管字符串传递给本机代码。我相信我必须使用<代码> MARSARAL <代码>类来将字符串(从C→)转换为C++ >代码> const char */COD>。如果有更好的办法,我当然愿意。如果没有,我将使用这种方法。基本上,我希望在转换为
const char*
时确保没有内存泄漏。