"Fred Paris" <> wrote in message
news

...
> Hi
>
> I'm writing a class to act as a wrapper around a C library.
>
> This C library exposes functions like:
>
> SetSomeInfo( char *pTheInfo );
>
> In my wrapper class, the info in question is in a STL string.
>
> std::string m_TheInfo;
>
> So inside the wrapper class I would like to call:
>
> SetSomeInfo( m_TheInfo.c_str() );
The following should get you through compilation...but really ask yourself
if that is really what you want (notice the low level operations and
explicit exception handling which are rather ugly):
char* buff = new char[m_TheInfo.length() + 1];
std::copy(buff, m_TheInfo.begin(), m_TheInfo.end());
buff[m_TheInfo.length()] = '\0';
try
{
SetSomeInfo(buff);
}
catch (...)
{
delete[] buff;
throw;
}
delete[] buff;
>
> But, problem:
>
> c_str returns a const char *, and SetSomeInfo accepts a char * (not
> const), so it doesn't compile. Maybe SetSomeInfo is poorly written,
> because it should have const in its signature, but it's not mine and
> I have no control over it.
>
> So my (rather ugly) workaround right now is:
>
> char *p = (char *)(DWORD) m_TheInfo.c_str() ; //get rid of const
Don't do this. You may corrupt the string object and your program may not
recover from such brutal operation. NOT COOL!! std::string::c_str() returns
a const char* for a reason, most likely to set up protection against misuse.
>
> but surely there has to be a more standard way ?
>
> Thanks
>