using StringToHGlobalAnsi should return a LPCTSTR.
> Here's what I try :
>
[quoted text clipped - 6 lines]
>
> thanks
> Here's what I try :
>
> LPCTSTR tst = (LPCTSTR) (LPCWSTR) Marshal::StringToHGlobalUni(str);
try
LPCTSTR string2 =
reinterpret_cast<LPCTSTR>(Marshal::StringToHGlobalAnsi(ret).ToPointer());
don't forget to use FreeHGlobal when done.
hth
Ben
Ben Schwehn - 06 Jul 2004 18:10 GMT
> try
> LPCTSTR string2 =
> reinterpret_cast<LPCTSTR>(Marshal::StringToHGlobalAnsi(ret).ToPointer());
>
> don't forget to use FreeHGlobal when done.
for completeness:
String^ testString = gcnew String("Test");
IntPtr ptr = Marshal::StringToHGlobalAnsi(testString);
LPCTSTR string = reinterpret_cast<LPCTSTR>(ptr.ToPointer());
//do stuff with string
Marshal::FreeHGlobal(ptr);
Ben
Ben Schwehn - 06 Jul 2004 19:11 GMT
and here's a different method taken from Stan Lippman's blog
(http://weblogs.asp.net/slippman/).
this converts to a char array, which you should easily be able to
convert to LPTCSTR
note that vcclr.h is included
#include <stdlib.h>
#include <vcclr.h>
#include <string>
using namespace System;
bool To_CharStar( String^ source, char*& target )
{
int len = (( source->Length+1) * 2);
target = new char[ len ];
pin_ptr<const wchar_t> wch = PtrToStringChars( source );
return wcstombs( target, wch, len ) != -1;
}
bool To_string( String^ source, string &target )
{
int len = (( source->Length+1) * 2);
char *ch = new char[ len ];
bool result ;
{
pin_ptr<const wchar_t> wch = PtrToStringChars( source );
result = wcstombs( ch, wch, len ) != -1;
}
target = ch;
delete ch;
return result;
}
> Here's what I try :
>
[quoted text clipped - 6 lines]
>
> thanks
// Implementation
#include <string>
std::string convert(System::String * s)
{
const char * c = (const char
*)(System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(s)).ToPointer();
std::string str = c;
System::Runtime::InteropServices::Marshal::FreeHGlobal(System::IntPtr((void
*)c));
return str;
}
// Usage:
LPCTSTR tst = convert(str).c_str();
ppcdev - 21 Jul 2004 15:41 GMT
Thank you very much for your help that I've read only today !!!
I've also found an alternative using the wsprintf("%S"...) function...
see you
> > Here's what I try :
> >
[quoted text clipped - 22 lines]
>
> LPCTSTR tst = convert(str).c_str();
tom_usenet - 21 Jul 2004 16:10 GMT
>> Here's what I try :
>>
[quoted text clipped - 22 lines]
>
>LPCTSTR tst = convert(str).c_str();
That has the same problem as the original code - tst becomes a
dangling pointer straight after the ;.
Tom
Julie - 21 Jul 2004 16:24 GMT
> >> Here's what I try :
> >>
[quoted text clipped - 27 lines]
>
> Tom
Duh, right.
I use it in function calls, and never keep a pointer around to the underlying
c_str(), it was merely for (flawed!) illustrative purposes, thanks for pointing
it out.
Updated usage:
(immediate)
void SomeFunc(LPCTSTR input);
SomeFunc(convert(str).c_str());
(persistent)
std::string s = convert(str);