I'm currently using C++Builder to create an application that copies text to the user's clipboard. I've placed a TMemo control and I want to contain that in a const char * variable as seen in the code below:
const char* output = TMemo1->Text;
When I compile the program it throws the error
no viable conversion from 'Vcl::Controls::TCaption' (aka 'System::UnicodeString') to 'const char *'
Here's the code that copies text to the clipboard:
const char* output = TMemo1->Text; // Error here
const size_t len = strlen(output) + 1;
HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len);
memcpy(GlobalLock(hMem), output, len);
GlobalUnlock(hMem);
OpenClipboard(0);
EmptyClipboard();
SetClipboardData(CF_TEXT, hMem);
CloseClipboard();
The
Textproperty returns aUnicodeStringobject, not aconst char*pointer. And there is no implicit conversion fromUnicodeStringtoconst char*(nor do you want one). So you would have to convert the data manually, such as withWideCharToMultiByte()(or equivalent), eg:Alternatively, you can save the
TMemo's text to anAnsiStringand let the RTL handle the conversion for you, eg:However, since you are dealing with Unicode text, you should be using the
CF_UNICODETEXTformat instead ofCF_TEXT. That way, you don't need to convert theUnicodeStringdata at all, you can just store it as-is (if anybody requestsCF_TEXTfrom the clipboard afterwards, the clipboard itself will convert the text for you), eg:That being said, you are making things harder for yourself then you need to. The VCL has a
TClipboardclass that handles all of these details for you, eg: