Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'System::String ^' to 'LPCWSTR'

I want to convert System::String ^ to LPCWSTR.

for

FindFirstFile(LPCWSTR,WIN32_FIND_DATA); 

Please help.

like image 494
Rick2047 Avatar asked Jun 30 '09 10:06

Rick2047


2 Answers

To convert a System::String ot LPCWSTR in C++/CLI you can you use the Marshal::StringToHGlobalAnsi function to convert managed strings to unmanaged strings.

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);
like image 89
heavyd Avatar answered Oct 27 '22 22:10

heavyd


The easiest way to do this in C++/CLI is to use 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);
}
like image 28
Bojan Resnik Avatar answered Oct 27 '22 21:10

Bojan Resnik