CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    May 1999
    Posts
    92

    CString ------> LPSTR

    How can I convert a CString variable to a LPSTR variable?


  2. #2
    Join Date
    Apr 1999
    Posts
    90

    Re: CString ------> LPSTR

    That may depend on whether or not you'll be modifying the LPSTR.


  3. #3
    Join Date
    Apr 1999
    Posts
    90

    Re: CString ------> LPSTR

    Look at the example supplied with the CString::GetBuffer() description in the VC++ help.

    It returns a LPTSTR, but unless you're using UNICODE, it should be the same thing.


  4. #4
    Join Date
    Apr 1999
    Posts
    9

    Re: CString ------> LPSTR

    I use a simple little macro that casts the string class to a pointer The macro is below

    #define CHARPTR(CMyString) (LPSTR)((LPCTSTR)(CMyString))

    CMyString is the name of the string class variable. Then wherever you need to change to a string pointer you use CHARPTR(CMyString). Remember however that any LPSTR variable has to have the appropriate memory set aside, otherwise you will potentially clobber your program.


  5. #5
    Join Date
    Apr 1999
    Posts
    90

    Re: CString ------> LPSTR

    We shouldn't be showing beginners how to do that. It's an extremely unsafe way to do it. Especially if the developer using the macro doesn't know you've simply typecast your way from a const to a non-const and then assumes that it can be modified. It may introduce a bug that can be difficult to track down.


  6. #6
    Join Date
    Apr 1999
    Posts
    9

    Re: CString ------> LPSTR

    True there is a danger in using this macro if it is used incorrectly. However it can be safely implemented, by using the macro to make a char array copy of the CString in situations where legacy code only accepts char pointers. Additionally it can be used as a function parameter if ( and this is obviously a major caveat), the function is known not to change the passed parameter or where the compiler makes local copies of the passed parameter.

    It is important to remember that it is a macro and therefore does not have any error checking etc.,and any usage needs to take that into account.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured