C++ Convert Sytem::String^ to LPCOLESTR

社会主义新天地 提交于 2020-01-03 04:53:08

问题


I write in mixed mode (C++/CLI) and I can not resolve this problem:

String ^progID = "Matrikon.OPC.Server";
CLSID clsid;
HRESULT result = CLSIDFromProgID(progID, &clsid);

error C2664: 'CLSIDFromProgID' : cannot convert parameter 1 from 'System::String ^' to 'LPCOLESTR'

How can I convert String^ to LPCOLESTR ?
Thanks!


回答1:


First, lets convert System::String to char*

IntPtr p = Marshal::StringToHGlobalAnsi(progID); char *pNewCharStr = static_cast<char*>(p.ToPointer());

second, casting char * to LPCOLESTR using ATL conversion macro:

LPCOLESTR converted_string = A2COLE(pNewCharStr);




回答2:


I made another way:

// 1.
pin_ptr<const WCHAR> str = PtrToStringChars(progID);
LPCOLESTR coleString = (LPWSTR)str; 

I have found that pin_ptr will be released if goes out of scope
Define the Scope of Pinning Pointers and
pin_ptr (C++/CLI)
This code works well for me:

// 2. this is the same like (1.)
String ^progID2 = "Matrikon.OPC.Simulation.1";// This is example of dynamic string
pin_ptr<const WCHAR> PINprogID2 = PtrToStringChars(progID2);
CLSID clsid2;
HRESULT result2 = CLSIDFromProgID(PINprogID2, &clsid2); //(LPCOLESTR, &CLSID)


Another example:

// 3.
pin_ptr<const WCHAR> sclsid3 = PtrToStringChars("{63D5F432-CFE4-11d1-B2C8-0060083BA1FB}");
CLSID clsid3;
CLSIDFromString((WCHAR*)sclsid3, &clsid3); //(LPOLESTR, &CLSID)

I am not much experienced and I am not sure if there are some lack of memory, but I think those codes are correct.




回答3:


Avoid using the hammer for every nail. C++/CLI lets you just as easily use native types. So it is simply:

LPCOLESTR progid = L"Matrikon.OPC.Server";
// etc..

Non-zero odds (always say why) that you can simply use Type::GetTypeFromProgID().



来源:https://stackoverflow.com/questions/23972044/c-convert-sytemstring-to-lpcolestr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!