Ric*_*047 10 .net clr winapi visual-c++
我想转换System::String ^为LPCWSTR.
对于
FindFirstFile(LPCWSTR,WIN32_FIND_DATA);
Run Code Online (Sandbox Code Playgroud)
请帮忙.
Boj*_*nik 25
在C++/CLI中执行此操作的最简单方法是使用pin_ptr:
#include <vcclr.h>
void CallFindFirstFile(System::String^ s)
{
WIN32_FIND_DATA data;
pin_ptr<const wchar_t> wname = PtrToStringChars(s);
FindFirstFile(wname, &data);
}
Run Code Online (Sandbox Code Playgroud)
hea*_*vyd 10
要在C++/CLI中转换System :: String或LPCWSTR,您可以使用Marshal :: StringToHGlobalAnsi函数将托管字符串转换为非托管字符串.
System::String ^str = "Hello World";
IntPtr ptr = System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(str);
HANDLE hFind = FindFirstFile((LPCSTR)ptr.ToPointer(), data);
System::Runtime::InteropServices::Marshal::FreeHGlobal(ptr);
Run Code Online (Sandbox Code Playgroud)
您需要使用 P/Invoke。检查此链接:http://www.pinvoke.net/default.aspx/kernel32/FindFirstFile.html
只需添加DllImport本机函数签名:
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
static extern IntPtr FindFirstFile
(string lpFileName, out WIN32_FIND_DATA lpFindFileData);
Run Code Online (Sandbox Code Playgroud)
CLR 将自动管理本机类型封送处理。
[编辑]我刚刚意识到您正在使用 C++/CLI。在这种情况下,您还可以使用隐式 P/Invoke,这是只有 C++ 支持的功能(与 C# 和 VB.NET 相反)。本文展示了几个示例: