标准警告:虽然当然可以用 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!