cannot convert parameter 1 from 'System::String __gc *' to 'LPCSTR'
Hi,
I am trying to pass comport name via combobox in managed c++.net but cant seen to get it to work. It returns with the erro message
cannot convert parameter 1 from 'System::String __gc *' to 'LPCSTR'
Can someone help me
This is my function.
String * commPort = commPortsBox->Items->Item[i]->ToString();
HANDLE hCom= ::CreateFile(commPort,GENERIC_WRITE | GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);
Thanks.
Re: cannot convert parameter 1 from 'System::String __gc *' to 'LPCSTR'
I have managed to get it working.
System::String * str = commPortsBox->Items->Item[i]->ToString();
char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);
HANDLE hCom= ::CreateFile(str2 ,GENERIC_WRITE | GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);
Thanks.
Re: cannot convert parameter 1 from 'System::String __gc *' to 'LPCSTR'
Re: cannot convert parameter 1 from 'System::String __gc *' to 'LPCSTR'
Quote:
I have managed to get it working.
System::String * str = commPortsBox->Items->Item[i]->ToString();
char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);
HANDLE hCom= ::CreateFile(str2 ,GENERIC_WRITE | GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);
Firstly, you're not releasing the memory you're allocating - and even worse it's global memory causing a global memory leak.
Secondly, this is a huge amount of effort for what is effectively a very simple operation.
See my article here.
Darwen.
Re: cannot convert parameter 1 from 'System::String __gc *' to 'LPCSTR'
@ darwen
I have changed the code to as per your suggestion. 'Marshal::FreeHGlobal(commName)' has been used to free the memory. Is there anything wrong with this code as it stands?
System::String * comm = commPortsBox->SelectedItem->ToString();
char* commName = (char*)(void*)Marshal::StringToHGlobalAnsi(comm);
HANDLE hCom= ::CreateFile(commName,GENERIC_WRITE | GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);
Marshal::FreeHGlobal(commName);
Re: cannot convert parameter 1 from 'System::String __gc *' to 'LPCSTR'
It's ok as it stands however I prefer to do it as I've said in the article as this doesn't use global memory.
Darwen.