Convert char[100] to LPTSTR
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 25

Thread: Convert char[100] to LPTSTR

  1. #1
    Join Date
    Jun 2005
    Posts
    44

    Convert char[100] to LPTSTR

    HI All ,

    i have a function whose return type is LPTSTR.

    LPTSTR GetValidName()
    {
    char buf [100];

    return buf;
    }

    i have removed a few lines from the function.

    As u can see buf is a local variable and will not be available after the function exits.

    THe compiler issues a warning for the above code.

    I don't want to change the return type to a CString or a string.

    what extra code should i write for the function to be appropriate.



    Thanks

  2. #2
    Join Date
    Aug 2004
    Posts
    294

    Re: Convert char[100] to LPTSTR

    char -> TCHAR
    Boris Karadjov
    Brainbench MVP for Visual C++
    http://www.brainbench.com/

  3. #3
    Join Date
    Jun 2005
    Posts
    44

    Re: Convert char[100] to LPTSTR

    the problem is with returning.

    char can be a TCHAR also but it will be a local variable. and after returning the scope ends.

    how do we solve this ?

  4. #4
    Join Date
    Aug 2004
    Location
    Bucharest, Romania... sometimes
    Posts
    1,039

    Re: Convert char[100] to LPTSTR

    Following implementation should not be used by multiple threads without locking, because the static variable is shared:
    Code:
    /*
    	Not thread safe function, 'cause it uses a static variable.*/
    LPTSTR GetValidName() {
    	static TCHAR buf [100];
    	return buf;
    }
    If you have multi-threaded calls to this function, I can suggest other implementation.
    Best regards,
    Bogdan Apostol
    ESRI Developer Network

    Compilers demystified - Function pointers in Visual Basic 6.0
    Enables the use of function pointers in VB6 and shows how to embed native code in a VB application.

    Customize your R2H
    The unofficial board dedicated to ASUS R2H UMPC owners.

  5. #5
    Join Date
    Oct 2002
    Location
    Germany
    Posts
    6,205

    Re: Convert char[100] to LPTSTR

    Quote Originally Posted by Kris_V
    the problem is with returning.
    Correct.
    Quote Originally Posted by Kris_V
    char can be a TCHAR also but it will be a local variable. and after returning the scope ends.
    But, not necessarily so... (else, why would people use type TCHAR at all?) It depends on the pre-processor macros in use.

    TCHAR can also be wchar_t - a wide character - when _UNICODE is defined... Anyways, do you really need to return a LPTSTR? That scenario seems avoidable here.

    In general, convert a LPSTR (i.e. char*) to LPTSTR (i.e. TCHAR*) using conversion class CA2T.

    Like this -
    Code:
    CA2T pszConvertedString (buf);
    
    // Use pszConvertedString as a LPTSTR 
    Quote Originally Posted by Kris_V
    how do we solve this ?
    Allocate memory on the heap using new, copy the buffer to this memory, and return that pointer. So, an extension to that conversion code above would be -
    Code:
    LPTSTR GetValidName()
    {
      char buf [100] = {0};   // Remember to copy a string to this buffer!
    
      CA2T pszConvertedString (buf);
    
      TCHAR * pszAllocatedReturnBuf = new TCHAR [_tcslen (pszConvertedString) + 1];
      _tcscpy (pszAllocatedReturnBuf, pszConvertedString);
    
      // Caller must free
      return pszAllocatedReturnBuf;
    }
    Last edited by Siddhartha; April 1st, 2006 at 09:59 AM.

  6. #6
    Join Date
    May 2005
    Posts
    4,954

    Re: Convert char[100] to LPTSTR

    another way is simply send pointer to array:

    Code:
    void GetValidName(char *buf, int len)
    {
      //do someting with buf ( just make sure you dont setting/reading value above len )
    
    }
    
      // usage
      char buf[MAX_PATH]={0};
      GetValidName(buf,sizeof(buf));

    Cheers
    If a post helped you dont forget to "Rate This Post"

    My Article: Capturing Windows Regardless of Their Z-Order

    Cheers

  7. #7
    Join Date
    Feb 2000
    Location
    San Diego, CA
    Posts
    10,354

    Re: Convert char[100] to LPTSTR

    Quote Originally Posted by Siddhartha
    Allocate memory on the heap using new, copy the buffer to this memory, and return that pointer.
    This is fine, but has potential problems of how to deallocate. Especially, if this function is exported by a DLL or such. For one, the function has to be documented saying it allocates memory, and also what form of memory allocation was used, so the caller can use the proper deallocation routine.

    Also, in case of DLLs, the module that allocated also has to deallocate. So, you would now have to provide a routine to deallocate.

    All this , if this is being called from another module. But just wanted to point it out.

  8. #8
    Join Date
    Oct 2002
    Location
    Germany
    Posts
    6,205

    Re: Convert char[100] to LPTSTR

    Quote Originally Posted by kirants
    This is fine, but has potential problems of how to deallocate. Especially, if this function is exported by a DLL or such.
    Well... This function isn't exported - according to the problem statement in the OP. I suggested that solution given the problem statement of returning a LPTSTR.

    However, lets not ignore this line -
    Quote Originally Posted by Me
    Anyways, do you really need to return a LPTSTR? That scenario seems avoidable here.
    Good that you make that point... GS' suggested way would be the thing to do.
    Last edited by Siddhartha; April 2nd, 2006 at 04:54 AM.

  9. #9
    Join Date
    Feb 2000
    Location
    San Diego, CA
    Posts
    10,354

    Re: Convert char[100] to LPTSTR

    Quote Originally Posted by Siddhartha
    I suggested that solution given the problem statement of returning a LPTSTR.
    Agree. The OP started off with the statement that changing the function signature wasn't an option, so there is not much one can suggest

  10. #10
    Join Date
    Jun 2005
    Posts
    44

    Re: Convert char[100] to LPTSTR

    Those were good amount of info gurus....

    i felt what Bornish suggested as appropriate (using a static variable).

    but he also said that in a multithreaded environment extra care has to be taken.

    Bornish, can u suggest what needs to be done in a multithreaded environment ?

    Thanks once again for the inputs

  11. #11
    Join Date
    Aug 2004
    Location
    Bucharest, Romania... sometimes
    Posts
    1,039

    Re: Convert char[100] to LPTSTR

    http://www.codeguru.com/forum/newrep...eply&p=1364659

    Quote Originally Posted by Kris_V
    Those were good amount of info gurus....

    i felt what Bornish suggested as appropriate (using a static variable).

    but he also said that in a multithreaded environment extra care has to be taken.

    Bornish, can u suggest what needs to be done in a multithreaded environment ?

    Thanks once again for the inputs
    If multiple threads may call that function at the same time, then it is not a good idea to use a static local variable which can be changed by one thread while used in another thread. If such static variable exists, the function implementation should assure proper usage by implementing a locking mechanism (critical section, semaphore, mutex, RAII lock...) while using this shared static variable. Locking can be time expensive, thus is recommended to be avoided. If calls to this function are from one thread only, then keep the static variable. Else, either temporary lock calls, or use per thread variables. Thread Local Storage (TLS) is quite recommended for such situations.
    Best regards,
    Bogdan Apostol
    ESRI Developer Network

    Compilers demystified - Function pointers in Visual Basic 6.0
    Enables the use of function pointers in VB6 and shows how to embed native code in a VB application.

    Customize your R2H
    The unofficial board dedicated to ASUS R2H UMPC owners.

  12. #12
    Join Date
    Oct 2002
    Location
    Germany
    Posts
    6,205

    Re: Convert char[100] to LPTSTR

    Actually, you need to explain why this -
    Quote Originally Posted by Kris_V
    i felt what Bornish suggested as appropriate (using a static variable).
    ...Was appropriate?

    Using a static array would actually not be my recommended way of doing it.
    (Although, in a single threaded scenrio it would work just as fine.)

    In my opinion, this -
    Quote Originally Posted by Kris_V
    he also said that in a multithreaded environment extra care has to be taken.
    ...Is by far the greatest drawback not existent in other methods.
    Last edited by Siddhartha; April 3rd, 2006 at 07:51 AM.

  13. #13
    Join Date
    Aug 2004
    Location
    Bucharest, Romania... sometimes
    Posts
    1,039

    Re: Convert char[100] to LPTSTR

    Quote Originally Posted by Siddhartha
    Actually, you need to explain why this - ...Was appropriate?

    Using a static array would actually not be my way of doing it.

    In my opinion, this - ...Is by far the greatest drawback not existent in other methods.
    Well Sid, let me explain:
    - Imagine this being a private method of a thread class... or a derived class from one MFC class (also single-threaded implementation)... then a static local will suffice and removes the overhead of releasing memory after usage. Moveover, could be faster by not allocating and deallocating memory everytime the function is called.
    - Imagine this function being used in retrieving error messages in a multi-threaded environment. Per-thread variables are perfect solution for it. Each thread can store and retrieve its own errors without overwriting or locking. Such variables will be allocated when a thread starts and released when the thread ends... not every time a function is called.

    But, everyone is entitled to an oppinion.

    Regards,
    Bogdan Apostol
    ESRI Developer Network

    Compilers demystified - Function pointers in Visual Basic 6.0
    Enables the use of function pointers in VB6 and shows how to embed native code in a VB application.

    Customize your R2H
    The unofficial board dedicated to ASUS R2H UMPC owners.

  14. #14
    Join Date
    Oct 2002
    Location
    Germany
    Posts
    6,205

    Re: Convert char[100] to LPTSTR

    Quote Originally Posted by Bornish
    Well Sid, let me explain...
    Actually, the motive was pretty evident.

    However, what you point out as advantages are actually the method's undoing.
    Quote Originally Posted by Bornish
    Imagine this being a private method of a thread class... or a derived class from one MFC class (also single-threaded implementation)... then a static local will suffice and removes the overhead of releasing memory after usage.
    Private member... ?
    Sounds like you just stepped on a minefield.

    Rather than have a private member that returns a static buffer instantiated within it, I would have preferred that the buffer be a static private member too.
    Quote Originally Posted by Bornish
    Moveover, could be faster by not allocating and deallocating memory everytime the function is called.
    I dont think one should worry about performance here, because -
    1. Memory allocated to strings are typically released. Should a programmer be expected to treat one particular string pointer differently? This may be possible inside one function - but, not maintainable outside it (the OP's case).
    2. If a class returns a string pointer that wasn't previously allocated for, likelyhood is that the client would be tempted to release. That would be consistent. However, this would crash on a static pointer.
    3. What if Func1 returns a pointer returned by Func2 that returns your static string pointer? Till what level should one worry about not releasing a pointer?
    I favour maintainability, and reliability to performance.
    Also, I typically believe in measuring performance before I comprimise any of those two for it.

    Of course, this is my opinion.

  15. #15
    Join Date
    Aug 2004
    Location
    Bucharest, Romania... sometimes
    Posts
    1,039

    Re: Convert char[100] to LPTSTR

    Maybe the function return type should be changed from LPTSTR to LPCTSTR for ppl like you to understand how to use that function.
    Quote Originally Posted by Siddhartha
    Rather than have a private member that returns a static buffer instantiated within it, I would have preferred that the buffer be a static private member too.
    The only difference between having a local static variable declared in the private member function and a private member variable is localization (lazy initialization, or create on request). I prefer localization. Also, I prefer not having a class defined with a lot of junk of intermediar variables used in processing, even if their lifetime is longer (as static member data have).

    In the end, I'd rather take the time to implement per-thread variables for as many reasons I can think of:
    - thread safe
    - speed optimization
    - can be dynamically reallocated (if required)
    - returned as const will not confuse anyone (and produce crashes or memory leaks)

    Best regards,
    Bogdan Apostol
    ESRI Developer Network

    Compilers demystified - Function pointers in Visual Basic 6.0
    Enables the use of function pointers in VB6 and shows how to embed native code in a VB application.

    Customize your R2H
    The unofficial board dedicated to ASUS R2H UMPC owners.

Page 1 of 2 12 LastLast

Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center