How do I use String class in CRT Fuctions

J

John E Katich

How can I cast a String to a const wchar_t*?

Ths following code genreates a compile error:

error C2664: '_wsplitpath' : cannot convert parameter 1 from 'System::String
__gc *' to 'const wchar_t *'


OpenFileDialog* ofd = new OpenFileDialog();
ofd->Filter = "OW Files|*.db;aepctl.dat;aepord.dat;aep|All Files|*.*";
if(ofd->ShowDialog() == DialogResult::OK)
{
wchar_t drive[_MAX_DRIVE];
wchar_t dir[_MAX_DIR];
wchar_t fname[_MAX_FNAME];
_wsplitpath( ofd->FileName ,drive,dir,fname,NULL);
}
 
W

William DePalo [MVP VC++]

John E Katich said:
How can I cast a String to a const wchar_t*?

It's not actually a cast but this will do the job on an instance s of
System::String

#include <vcclr.h>

wchar_t __pin *pStr;

pStr = PtrToStringChars(s);

Regards,
Will
 
F

Frisky

You can also use

Char * ppchar = PtrToStringChars( mystring ); // __pin not needed
for( ; ppchar != 0; ++ppchar )
{
// do stuff with each Char
}

PtrToStringChars returns a System::Char*, which is an interior pointer. As
such, it is subject to garbage collection. You don't have to pin this
pointer unless you're going to pass it to a native function.

Pinning is not needed because ppchar is an interior pointer, and if the
garbage collector moves the string it points to, it will also update ppchar.
Without __pin the code will work and not have the potential performance hit
caused by pinning.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top