Tuesday, November 6, 2012

String^ to const char* C++/CX

So today I was looking to convert a textBox text field into a const char to use as an IP address to send data to. This wasn't exactly easy to find any info on so I had to write this post.

First I needed to get the String^ from the textBox xaml object like this
String^ s = IPAddress->Text;
this assumes that the textBox is named "IPAddress".
then make a size_t object and i'll call it i, this was needed to set the data size for the wcstombs_s function at the end. Not exactly sure what this is used for, but this is working, so if anyone has any good understanding of this function then please fill me in down in the comments below.

String^ s = IPAddress->Text;
size_t   i;
const wchar_t* cw = s->Data();
char *c= new char[s->Length()+1];
memset(c,0,s->Length()+1);
wcstombs_s(&i, c, (size_t)s->Length()+1,  s->Data(), (size_t)s->Length()+1 );
SomeClientFunction.SetIPAddress(c);

then I make the const wchar_t* pointer and use the s->Data() to satisfy that.
then i make a new char[] array with the length of the String^ this is pretty simple. so char[s->Length() + 1] is how that's done.
then I have to allocate the memory for the char*c using memset, pretty easy here.
then the weird wcstombs_s which is needed since wcstombs was depricated, so i needed to use the safe version of it to get past the WinRT checks. I guess this is a memory security thing.
now the new safe version of the function asks for the &i which im not sure what does, then you add in the target char array then set a size, then give it a source using s->Data(), then tell it how long that array is.
and that's that, worked for me!

I'll also note that my SomeClientFunction was expecting (const char * ip) in it's args.

I just use this blog to help remind me how I did things in general.

hope this helps someone.

edit:
So the &i is a returned value that's the size of the actual c in this case. Since c could actually be shorter than the original size allocated for it when using some other methods to create the size of c.

No comments:

Post a Comment

rxokita's shared items