Hi NG!
In a managed C++ class, I have a function that expects a System::String
argument that specifies a file name. Now I want to use that filename for
CreateFile, but I don't know how to convert a System::String to a
LPCTSTR. (Yes, I know that I could use System::IO::StreamReader - I want
to do it that way anyway, just for testing purpose).
Can anyone give me a hint how to do this?
Thanks in advance!
Best regards,
Michael

Signature
http://www.mkcs.at/
The specified e-mail-address is valid and will be read.
Peteroid - 03 Mar 2005 22:05 GMT
I asked a similar question a few days ago here (but it is far down, so you
probably didnt see it). I asked how to convert a String* to a char[]. This
is how I ended up doing it:
char char_array[32+1] ;
String* string_thing = new String("Hello") ;
for ( int c=0 ; c < length ; c++)
{
char_array[c] = char(string_thing->chars[c]) ;
}
char_array[length] = '\0' ;
After this code is executed: char_array contains null-terminated "Hello".
So, in your case the 'string_thing' is your filename argument and char_array
is similar to char* (it is easy to change to using char* instead, as
char_array is almost a char*....hehe).
Hope this helps... :)
[==Peteroid==]
> Hi NG!
>
[quoted text clipped - 11 lines]
>
> Michael
Steve McLellan - 04 Mar 2005 17:11 GMT
I think this should do it.. (first one is String * to stl string, second is
the opposite. You can extract the raw char pointer from an STL string using
c_str().
std::string STLStringFromDotNetString( System::String *str)
{
//get a pointer to an array of ANSI chars
char *chars = (char*) Marshal::StringToHGlobalAnsi(str).ToPointer();
//assign the array to an STL string
std::string stl = chars;
//free the memory used by the array
//since the array is not managed, it will not be claimed by the garbage
collector
Marshal::FreeHGlobal(chars);
return stl;
}
System::String * DotNetStringFromSTLString( const std::string &str)
{
return Marshal::PtrToStringAnsi((int*) str.c_str());
}
Steve
> Hi NG!
>
[quoted text clipped - 11 lines]
>
> Michael