【问题标题】:C++ CLI System.String^ to MFC LPCTSTRC++ CLI System.String^ 到 MFC LPCTSTR
【发布时间】:2012-04-04 16:13:40
【问题描述】:

如何将系统 (.net) C++\CLI String^ 转换为 MFC C++ LPCTSTR 字符串。

LPCTSTR 转换为String^ 非常容易,但到目前为止还没有发现相反的方法。

【问题讨论】:

  • 请注意 LPCTSTR 只是一个 char 指针,所以也许您宁愿将 String 转换为 CString 或 std::string 然后获取指针,这样您就不必处理内存管理跨度>

标签: c++ string mfc c++-cli lpcstr


【解决方案1】:

如果您有 Visual Studio 2008 或更高版本,您应该能够使用 C++/CLI 编组库执行此操作,如下所示:

#include <msclr\marshal.h>

using namespace System;
using namespace msclr::interop;

...

String^ cliString;
marshal_context context;

LPCTSTR cstr = context.marshal_as<const TCHAR*>(cliString);

有关 MSDN 上类型间编组的更多信息:Overview of Marshaling in C++

【讨论】:

  • 为什么不使用 LPCTSTR tstr = context.marshal_as( cliString) 让构建环境处理实际的字符串类型?
  • 我已经接受了你的明智想法,但由于某种原因我已经忘记了。谢谢!
  • 这个元帅与其他答案中的元帅有什么区别?
  • 除了更好的语义外,使用marshal_context意味着分配的字符串在上下文被销毁时被销毁。另一方面,调用 Marshal::StringToHGlobalAuto 需要您 FreeHGlobal 返回的字符串。
【解决方案2】:

您可能想尝试Marshal::StringToHGlobalUniMarshal::StringToHGlobalAutoMarshal::StringToHGlobalAnsi

请记住,分配的非托管字符串需要使用Marshal::FreeHGlobal 释放。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-04
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    相关资源
    最近更新 更多