Question

Currently I'm busy to get some text from the textbox and then convert in into a const char*. I have the following code:

System::String^ host = textBoxHostadres->Text;
    const char* host2 = (const char*)(void*)Marshal::StringToHGlobalAnsi(host);
    //system(host2); //What to do with this?
    Marshal::FreeHGlobal(host2);

It gives a redline (Visual Studio 2012) under Marshal::FreeHGlobal. Can somebody give me a right direction to get the text from the textbox and get it to a const char*? The first line works well and through debugging I see the text get captured.

Update:

System::String^ host = textBoxHostadres->Text;
                pin_ptr<const wchar_t> wch = PtrToStringChars(host);

            // Convert to a char*
            size_t origsize = wcslen(wch) + 1;
            const size_t newsize = 100;
            size_t convertedChars = 0;
            char nstring[newsize];
            wcstombs_s(&convertedChars, nstring, origsize, wch, _TRUNCATE);
            strcat_s(nstring, " (char *)");

            const char* host2 = (const char*)(void*)Marshal::StringToHGlobalAnsi(host);
            system(host2);

            traceroute hostAddress(host2);
Was it helpful?

Solution

Here you will find all possible conversion between char *, wchar_t*, _bstr_t, CComBSTR, CString, basic_string, and System.String.

The strings types that are covered include char *, wchar_t*, _bstr_t, CComBSTR, CString, basic_string, and System.String. In all cases, a copy of the string is made when converted to the new type. Any changes made to the new string will not affect the original string, and vice versa.

Regarding the EDITs you've added:

It would be nice if you could at least try to understand the code you are copy-pasting. This line strcat_s(nstring, " (char *)"); adds some characters to your string and mainly (char *) and this is obvious now that your nstring doesn't contain an adress of a file allready, but adress + some trash. Also you don't need this line std::cout << nstring << std::endl; at all.

This is how your implementation should look like.

System::String^ host = textBoxHostadres->Text;
pin_ptr<const wchar_t> wch = PtrToStringChars(host);
// Convert to a char*
size_t origsize = wcslen(wch) + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
char nstring[newsize];  // nstring is an array of chars
wcstombs_s(&convertedChars, nstring, origsize, wch, _TRUNCATE);
// strcat_s(nstring, " (char *)");  this line adds trash to your nstring!!!
traceroute hostAddress(nstring);

OTHER TIPS

You were not type-casting host2 in your call to Marshal::FreeHGlobal():

System::String^ host = textBoxHostadres->Text;
const char* host2 = (const char*)(void*)Marshal::StringToHGlobalAnsi(host);
system(host2);
traceroute hostAddress(host2);
Marshal::FreeHGlobal((IntPtr) host2);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top