VC++2010中的String^到LPCTSTR(Windows窗体应用程序)

2024-06-22

如何将 System::string^ 转换为 LPCTSTR ? 因为我的要求是使用函数克隆文件CopyFile,如果我为其参数指定修复名称(OldFile.jpg 和 LatestFile.jpg),它就可以正常工作(下面的代码:工作正常)

LPCTSTR in_f,out_f;

in_f    =   _T("d:\\Old.jpg");
out_f   =   _T("d:\\Latest.jpg");

CopyFile(in_f,out_f,false);

上面的代码将 Old.jpeg 克隆到 Latest.jpg 中,但是当我尝试给出从某些字符串中出来的名称(Latest.jpg)时,它不会创建文件(下面的代码:不工作)

  String^   Name    =   "Latest";

//------Capture Current Date & Time
    DateTime datetime = DateTime::Now;

//-------Convert Date Timt in to String
    Name    =   Name + String::Format("{0}",datetime); 
    Name    =   Name->Replace('/','-');
    Name    =   Name->Replace(':','-');
    Name    =   Name    +   ".jpg";    

    LPCTSTR in_f,out_f;

    in_f    =   _T("d:\\Old.jpg");
    out_f   =   (LPCTSTR)Name; //Trying to Assign Current Latest file Name With date Time here

    CopyFile(in_f,out_f,false);

问题是 CopyFile 将 LPCTSTR 类型作为参数,因为我给出了类型 System::string^,所以建议我如何将此 System::string^ 转换为 LPCTSTR,以便我可以添加当前日期时间我的文件的名称。我正在使用 VC++2010 和 Windows 窗体应用程序


标准警告:虽然当然可以用 C++/CLI 编写应用程序的主体,甚至可以使用 WinForms 用 C++/CLI 编写 GUI,但不建议这样做。 C++/CLI 适用于互操作场景:当 C# 或其他 .Net 代码需要与非托管 C++ 交互时,C++/CLI 可以提供两者之间的转换。对于初级开发,如果需要托管代码,建议使用 C# 和 WinForms 或 WPF;如果需要非托管代码,建议使用 C++ 和 MFC。


我不确定我是否同意 Hans 的评论,即 TCHAR 已过时,但显式转换为宽字符串并调用CopyFileW是一个不错的选择。

此外,还可以转向另一个方向,从非托管字符串转换为托管字符串,并使用 .Net 方法复制文件,File::Copy(String^, String^, Boolean) https://msdn.microsoft.com/en-us/library/9706cfs5.aspx?cs-lang=cpp.

转换为LPCTSTR,我会使用 marshal_as。因为它是用模板实现的,所以编译器会解析你的LPCTSTR调用LPCSTR or LPCWSTR版本,视情况而定。

Microsoft 没有针对每个模板版本的专用文档页面marshal_as,但是C++ 中的编组概述 https://learn.microsoft.com/en-us/cpp/dotnet/overview-of-marshaling-in-cpp页面是一个很好的起点。

我的测试程序:

#include <msclr\marshal.h>

int main(array<System::String^>^ args)
{
    String^ managedStr = "I came from managed land!\r\n";

    // This controls the lifetime of the LPCTSTR that marshal_as returns. 
    // When this goes out of scope, the LPCTSTR will no longer be valid, 
    // so be aware of its lifetime.
    msclr::interop::marshal_context context;

    LPCTSTR unmanagedStr = context.marshal_as<LPCTSTR>(managedStr);

    OutputDebugString(unmanagedStr);

    return 0;
}

Result:

I came from managed land!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

VC++2010中的String^到LPCTSTR(Windows窗体应用程序) 的相关文章

随机推荐