Changing the text of a C++ CLI label - visual-c++

I am trying to change the text of a label in a C++ CLI program. I need to take a value the the user entered in a textbox, insert that into a short string, then change a label to that string. I have no problem constructing the string, but I am having trouble setting the label to the new string. Here is my code...
std::string v1str = "Phase A: ";
v1str.append(vt2); //vt2 is type str::string
v1str.append(" Vac");
label->Text = v1str;
This is the error message that I'm getting...
Why am I not allowed to pass v1str as the label text setter? How can I pass the string I've constructed to the label text setter?

Label::Text has a type of System::String^, which is a managed .Net string object. You cannot assign a std:string to a System::String^ directly becuase they are different types.
You can convert a std::string to a System::String. However you most likely just want to use the System::String type directly:
System::String^ v1str = "Phase A: ";
v1st += vt2; // or maybe gcnew System::String(vt2.c_str());
v1str += " Vac";
label->Text = v1str;

C++/CLI is not C++, you can't use std::string in there. But you can use C++ within C++/CLI, and convert std::string to and from System::String
//In C++/CLI form:
#include <vcclr.h>
System::String^ clr_sting = "clr_sting";
//convert strings from CLI to C++
pin_ptr<const wchar_t> cpp_string = PtrToStringChars(clr_sting);
//convert strings from C++ to CLI
System::String^ str = gcnew System::String(cpp_string);
//or
std::string std_string = "std_string";
System::String^ str2 = gcnew System::String(std_string.c_str());

Related

How to convert AnsiString to std::string in C++ Builder?

I would like to ask how can I get a text input from TEdit control and cast it to std::string (not AnsiString).
For example, if I have a TEdit control with the name User, I get the text from it with the User->Text command. What I want to do is to assign that value to a std::string, for example string my_str = User->Text;.
I would like to ask, how can I do this in C++ Builder? Is there some sort of a ToString() method or sort of, because I was not able to find one.
In C++Builder 2007 and earlier, TEdit::Text is an 8-bit AnsiString in the user's default ANSI locale. It is very straight forward to convert an AnsiString to a std::string - just use the AnsiString::c_str() method to get a null-terminated char* pointer to the AnsiString data, and then you can assign that to the std::string, eg:
std::string my_str = User->Text.c_str();
/* or:
System::AnsiSystem text = User->Text;
std::string my_str(text.c_str(), text.Length());
*/
If you want the std::string data to be in another character encoding, such as UTF-8, then you will have to convert the AnsiString data accordingly, such as with MultiByteToWideChar()/WideCharToMultiByte(), UTF8Encode(), etc, before assigning it to the std::string.
In C++Builder 2009 and later, TEdit::Text is a 16-bit UnicodeString in UTF-16 format. The easiest way to convert a UnicodeString to a std::string is to first convert to an AnsiStringT<CP> (where CP is the desired ANSI codepage - AnsiString uses CP=0, UTF8String uses CP=65001, etc), and then convert that to std::string, eg:
std::string my_str = AnsiString(User->Text).c_str(); // or UTF8String, etc...
/* or:
System::AnsiString text = User->Text; // or UTF8String, etc...
std::string my_str(text.c_str(), text.Length());
*/
Alternatively, in C++11 and later, you can convert the UnicodeString to a std::wstring first, and then use std::wstring_convert, eg:
#include <locale>
std::wstring my_wstr = User->Text.c_str();
/* or:
System::UnicodeString text = User->Text;
std::wstring my_wstr(text.c_str(), text.Length());
*/
// System::Char may be either wchar_t or char16_t, depending
// on which platform you are compiling for...
std::string my_str = std::wstring_convert<std::codecvt_utf8_utf16<System::Char>>{}.to_bytes(my_wstr);
I had a lot of those to migrate from Borland to Embarcadero Rio. So I created a method to do it.
#include <cwchar.h> //std::wcslen
char* __fastcall AnsiOf(wchar_t* w)
{
static char c[STR_CONV_BUF_SIZE];
memset(c, 0, sizeof(c));
WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, w, std::wcslen(w), c, STR_CONV_BUF_SIZE, NULL, NULL);
return c;
}
std::string my_str = AnsiOf((User->Text).c_str());

C++ Convert Sytem::String^ to LPCOLESTR

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!
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.
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().
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);

How to convert String^ to String in C++ CLI?

Whenever I try to directly assign a String variable to another String variable I get error found no suitable conversation.
So is there a way to convert String^ pointer to a non-pointer struct String ?
I want :
System::String a = System::String('X',256);
I don't want :
System::String^ a = %System::String('X',256);
No, there is not, because as Hans pointed out in a comment, System::String is immutable. You cannot assign it. You can only associate a handle with an entirely new System::String object.
BTW
System::String^ a = %System::String('X',256);
is incorrect, it should be
System::String^ a = gcnew System::String('X',256);
Use System::String a('X', 256);.

SHGetSpecialFolderPath to a System::String^

I'm trying to parse a SHGetSpecialFolderPath into a string, a System::String^ to be precise.
I'm now using this code:
TCHAR appDataPath;
SHGetSpecialFolderPath(0, appDataPath, CSIDL_APPDATA, false);
I've tried things like this, but it doesn't work either:
LPWSTR appDataPath;
SHGetSpecialFolderPath(0, appDataPath, CSIDL_APPDATA, false);
I just want to get a System::String^ like this:
System::String ^ loc_inst = appDataPath + "\\inst\\info.xml";
I don't think C++/CLI can automatically concatenate char arrays and assign them to a string handle. I think you need to instantiate a new System::String object like this:
System::String^ loc_inst = gcnew System::String(appDataPath);
loc_inst.Append("\\inst\\info.xml");
Or you could use a StringBuilder, but if you want to make a new String object I think you've got to use gcnew and a constructor.
Keep in mind that appDataPath is not a String but a char array that you have previously allocated. However, System::String allows you to pass in char arrays in one of its constructors.

C++/CLI String Conversions

I found this really nice piece of code that converts a string to a System:String^ as in:
System::String^ rtn = gcnew String(move.c_str()); // 'move' here is the string
I'm passing rtn back to a C# program. Anyways, inside the function where this code exists, I'm passing in a System::String^. I also found some code to convert a System:String^ to a string using the following code:
pin_ptr<const wchar_t> wch = PtrToStringChars(cmd); // 'cmd' here is the System:String
size_t convertedChars = 0;
size_t sizeInBytes = ((cmd->Length + 1) * 2);
errno_t err = 0;
char *ch = (char *)malloc(sizeInBytes);
err = wcstombs_s(&convertedChars,ch, sizeInBytes,wch, sizeInBytes);
Now I can use 'ch' as a string.
This, however, seems to be alot more work than converting the other way using the gcnew. So, at last my question is, is there something out there that will convert a System::String^ to string using a similar fashion as with the gcnew way?
Use VC++'s marshaling library: Overview of Marshaling in C++
#include <msclr/marshal_cppstd.h>
// given System::String^ mstr
std::string nstr = msclr::interop::marshal_as<std::string>(mstr);
this could be useful:
wchar_t *str = "Hi StackOverflow"; //native
String^ mstr= Marshal::PtrToStringAnsi((IntPtr)str); // native to safe managed
wchar_t* A=( wchar_t* )Marshal::StringToHGlobalAnsi(mstr).ToPointer(); // return back to native
don't forget using namespace System::Runtime::InteropServices;

Resources