【问题标题】:MFC built using /clr compiler option - CString/System::String conversion使用 /clr 编译器选项构建的 MFC - CString/System::String 转换
【发布时间】:2010-09-23 04:10:32
【问题描述】:

我有一个相当大的 MFC 应用程序,它刚刚从 VS6.0 迁移到 VS2008。这是一个非常痛苦的过程,但现在我想探索任何可能可用的托管代码选项。我能够使用 /clr 开关成功构建项目,这似乎让我可以访问托管类型。

我想知道 System::String 和 CString 之间的转换是否是自动的。我发现的 MSDN 文档表明这种转换不是自动的,但我没有发现这种情况。下面的所有三个示例都有效,并且 1 和 2 都由 MSDN 记录。我很好奇的是示例 3,它也有效,但我不知道为什么。 CurrentDirectory 属性返回一个指向托管堆的指针,String^,但为什么我可以将它分配给 CString?示例 3 到底在做什么以及内存管理的含义是什么?

示例 1)

marshal_context ^ context = gcnew marshal_context(); 字符串 ^env = System::Environment::CurrentDirectory; const char* env2 = context->marshal_as(env); AfxMessageBox(env2); 删除上下文;

示例 2)

CString s(System::Environment::CurrentDirectory); AfxMessageBox(s);

示例 3)

CString s = System::Environment::CurrentDirectory; AfxMessageBox(s);

【问题讨论】:

    标签: visual-studio-2008 .net-3.5 mfc clr


    【解决方案1】:

    您可以从 system::String 转到 CString,因为它们共享一个公共转换 (lptstr?) 从 CString 转到 System::String 总是需要 System::String^ test = gcnew System::String( CStringVar );

    【讨论】:

      【解决方案2】:

      选项 3 的工作原理与选项 2 几乎相同。 CString::operator= 对 System::String 有重载。不要忘记赋值运算符可以做的不仅仅是复制引用。

      本页: How to: Convert Between Various String Types 非常对混合应用很有用。 pin_ptr 很棒。

      小心散布托管代码。我还在一个大型 MFC 应用程序上工作,该应用程序转到 /clr,我有时希望我们只在选择的库中完成它。当调用堆栈上有很多托管本机转换时,它会使调试变得痛苦。还有performance considerations

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-02
        • 1970-01-01
        • 2014-04-26
        • 2013-10-09
        • 2014-08-23
        • 1970-01-01
        • 2011-09-07
        相关资源
        最近更新 更多