Haven't used Windows Form in a very long time and this is my first time using it in C++.
And so it's the first time I've encountered the use of ^ after data types and class objects, for example:
Void Form1::btnConvert_Click(System::Object^ sender, System::EventArgs^ e)
spooky stuff.
I'm trying to call a function which requires a long pointer to constant string, so const char* or LPCSTR.
const char* cPath = txtBoxPath->Text.c_str();
The problem is when I try to convert from string^ I receive the error:
error C2228: left of '.c_str' must have class/struct/union
type is 'System::String ^'
did you intend to use '->' instead?
So, now I'm in a bit of a pickle. Any suggestions? Maybe educate me a bit on this ^ symbol, cause I don't seem to find anything on it when googling.
You can convert the System::String
to a std::string
via:
// Requires:
#include <msclr/marshal_cppstd.h>
auto str = msclr::interop::marshal_as<std::string>(txtBoxPath->Text);
Once you have a std::string
, then c_str()
will provide you the const char*
:
const char* cPath = str.c_str();
Note that you can also use Marshal
to do the conversion directly, ie:
IntPtr tmpHandle = Marshal::StringToHGlobalAnsi(txtBoxPath->Text);
char *cPath = static_cast<char*>(tmpHandle.ToPointer());
// use cPath
Marshal::FreeHGlobal(tmpHandle); // Don't use cPath after this...
The ^ character denotes a managed pointer (or reference). txtBoxPath::Text is a reference of type System::String. You'll need to de-reference it to use the dot operator or just use ->.
For the System::String^ to char* try the following:
char* cPath = (char*)Marshal::StringToHGlobalAnsi(txtBoxPath->Text).ToPointer();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.