Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. How to return char*

How to return char*

Scheduled Pinned Locked Moved C / C++ / MFC
c++tutorialquestion
17 Posts 8 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Paulraj G

    Hi All, How to reyurn char* in c++? My code is

    extern "C" char* callFunction()
    {
    std::string stroutput = pObject->ProcessNumber("hi","hi");
    char* strout = new char [stroutput.size()+1];
    strcpy (strout, stroutput.c_str());
    return strout;
    delete[] strout;

    }

    Thanks in advance...

    G.Paulraj

    S Offline
    S Offline
    Software_Developer
    wrote on last edited by
    #6

    #include char *return_Char_Pointer(char *ptrChar)
    {
    ptrChar = "hello hi! I am returning a return char pointer (char *p)\n\n";
    return ptrChar;
    }

    int main(int argc, char* argv[])
    {
    char *ptrChar = new char[255];
    char *ptrChar1;
    ptrChar1 =return_Char_Pointer(ptrChar);

    printf("%s",ptrChar1);
    delete \[\]ptrChar;
    
    return 0;
    

    }

    C A 2 Replies Last reply
    0
    • _ _Superman_

      What you've done is almost correct. 2 things are not right. First, you cannot use extern "C" if you're using std::string because string is an object of the basic_string class. class is not understood by C. Second, you cannot delete the memory inside the function. Deletion has to be done by the caller. Also there is no point in having any statements after the return statement.

      «_Superman_»  _I love work. It gives me something to do between weekends.

      _Microsoft MVP (Visual C++)

      Polymorphism in C

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #7

      «_Superman_» wrote:

      First, you cannot use extern "C" if you're using std::string

      The extern "C" merely prevents name decoration of exported function or variable names, it has nothing to do with the underlying C++ code, which may use any classes internally.

      Unrequited desire is character building. OriginalGriff I'm sitting here giving you a standing ovation - Len Goodman

      _ 1 Reply Last reply
      0
      • L Lost User

        «_Superman_» wrote:

        First, you cannot use extern "C" if you're using std::string

        The extern "C" merely prevents name decoration of exported function or variable names, it has nothing to do with the underlying C++ code, which may use any classes internally.

        Unrequited desire is character building. OriginalGriff I'm sitting here giving you a standing ovation - Len Goodman

        _ Offline
        _ Offline
        _Superman_
        wrote on last edited by
        #8

        You're right. My mistake. :sigh:

        «_Superman_»  _I love work. It gives me something to do between weekends.

        _Microsoft MVP (Visual C++)

        Polymorphism in C

        L 1 Reply Last reply
        0
        • _ _Superman_

          You're right. My mistake. :sigh:

          «_Superman_»  _I love work. It gives me something to do between weekends.

          _Microsoft MVP (Visual C++)

          Polymorphism in C

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #9

          «_Superman_» wrote:

          My mistake.

          The first I've seen from you; you must be having a bad day! ;)

          Unrequited desire is character building. OriginalGriff I'm sitting here giving you a standing ovation - Len Goodman

          _ 1 Reply Last reply
          0
          • L Lost User

            «_Superman_» wrote:

            My mistake.

            The first I've seen from you; you must be having a bad day! ;)

            Unrequited desire is character building. OriginalGriff I'm sitting here giving you a standing ovation - Len Goodman

            _ Offline
            _ Offline
            _Superman_
            wrote on last edited by
            #10

            The worst. :omg: !!!EVER!!! Need to cool off :doh:. Going to the bar. :-D

            «_Superman_»  _I love work. It gives me something to do between weekends.

            _Microsoft MVP (Visual C++)

            Polymorphism in C

            1 Reply Last reply
            0
            • S Software_Developer

              #include char *return_Char_Pointer(char *ptrChar)
              {
              ptrChar = "hello hi! I am returning a return char pointer (char *p)\n\n";
              return ptrChar;
              }

              int main(int argc, char* argv[])
              {
              char *ptrChar = new char[255];
              char *ptrChar1;
              ptrChar1 =return_Char_Pointer(ptrChar);

              printf("%s",ptrChar1);
              delete \[\]ptrChar;
              
              return 0;
              

              }

              C Offline
              C Offline
              CPallini
              wrote on last edited by
              #11

              Are you posting bad code to set the enemy on the wrong track?

              If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
              This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
              [My articles]

              1 Reply Last reply
              0
              • S Software_Developer

                #include char *return_Char_Pointer(char *ptrChar)
                {
                ptrChar = "hello hi! I am returning a return char pointer (char *p)\n\n";
                return ptrChar;
                }

                int main(int argc, char* argv[])
                {
                char *ptrChar = new char[255];
                char *ptrChar1;
                ptrChar1 =return_Char_Pointer(ptrChar);

                printf("%s",ptrChar1);
                delete \[\]ptrChar;
                
                return 0;
                

                }

                A Offline
                A Offline
                Addy Tas
                wrote on last edited by
                #12

                You'd better use memcpy to copy the literal string to ptrChar. Doing it like the makes you call delete on statically allocated memory. The assignment just returns the address of the literal string Cheers, AT

                Cogito ergo sum

                1 Reply Last reply
                0
                • P Paulraj G

                  Hi All, How to reyurn char* in c++? My code is

                  extern "C" char* callFunction()
                  {
                  std::string stroutput = pObject->ProcessNumber("hi","hi");
                  char* strout = new char [stroutput.size()+1];
                  strcpy (strout, stroutput.c_str());
                  return strout;
                  delete[] strout;

                  }

                  Thanks in advance...

                  G.Paulraj

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #13

                  I am surprised this will compile given the 'delete' is unreachable. :) Anyway, just remove the delete and return strout to the caller. It is then the callers responsibility to free the memory.

                  ============================== Nothing to say.

                  A S 2 Replies Last reply
                  0
                  • L Lost User

                    I am surprised this will compile given the 'delete' is unreachable. :) Anyway, just remove the delete and return strout to the caller. It is then the callers responsibility to free the memory.

                    ============================== Nothing to say.

                    A Offline
                    A Offline
                    Addy Tas
                    wrote on last edited by
                    #14

                    Good one; make sure that you set the comiler warnings to max (4) and warnings as errors. That will at least make sure that something like this won't even compile. Cheers AT

                    Cogito ergo sum

                    1 Reply Last reply
                    0
                    • P Paulraj G

                      Richard and Superman, Thanks for your reply. Actaully i supposed to return std::string. The thing is, this is a dll. and i am calling this dll from c# application. If i return like

                      return "some value";

                      this is working fine. but if i return like,

                      char* str; or std::string str;

                      return str;

                      the output is not coming correctly. from c# i am calling like

                      String str = somefunctionname();

                      How can solve this issue?

                      G.Paulraj

                      S Offline
                      S Offline
                      Stefan_Lang
                      wrote on last edited by
                      #15

                      First of all, if your function is part of a DLL called from outside that DLL, then memory allocated inside your function may not be released by the caller! The reason is that the caller may not use the same memory mapping and therefore cannot manipulate the heap form your DLL. There are various ways around that: 1. the easiest is to provide a release function in addition to your original one. The only pupose of that function is to release the buffer you previously allocated, and the caller of your function should call it once it doesn't need your string anymore. 2. A somewhat better solution, and in fact widely used, is to add another parameter to your function: a string buffer that the caller must pass to your DLL, so cou can copy the resulting string into it. Of course you must verify the buffer is big enough or else issue an appropriate error or warning. You couls also provide an additional function that simply returns the size you require the buffer to be, so the caller could first call this function, then allocate the memory and pass the resulting buffer to your function. 3. There are other ways, such as using Shared memory, but I think that would be overkill. Here's a suggestion based on variant 2 above:

                      // yourfile.h
                      extern "C" std::size_t requiredSize();
                      extern "C" std::size_t getString(char* buffer);

                      // yourfile.cpp
                      char mystring[] = "hello world"; // just an example
                      std::size_t requiredSize() {
                      return sizeof(mystring) / sizeof(char); // an upper limit to the size required for getString
                      }
                      std::size_t getString(char* buffer) {
                      if (!buffer) // error: no buffer provided!
                      return 0; // response: 0 bytes copied
                      strcpy(buffer, mystring); // hope for the best and just copy
                      return requiredSize(); // return the length of the copied string
                      }

                      And here's how to use it from C++:

                      #include "yourfile.h"
                      void foo() {
                      std::size_t sz = requiredSize(); // inquire required size
                      char* mybuffer = new char[sz]; // allocate a sufficiently large buffer
                      getString(buffer); // get the string
                      puts(buffer); // do something with the string (in this case, print it)
                      delete [] buffer; // release the buffer
                      }

                      1 Reply Last reply
                      0
                      • L Lost User

                        I am surprised this will compile given the 'delete' is unreachable. :) Anyway, just remove the delete and return strout to the caller. It is then the callers responsibility to free the memory.

                        ============================== Nothing to say.

                        S Offline
                        S Offline
                        Stefan_Lang
                        wrote on last edited by
                        #16

                        The problem with that is: 1. The caller may not know what method was used to allocate the memory (e. g. malloc or new), or if it was allocated at all, or instead just points to a static buffer! (Of course you could put that kind of information into the function documentation) 2. The OP put this function into a library interface. If bound statically, that would not pose a problem, but if bound dynamically, as a DLL, this DLL may use a separate heap - that means the caller may not even be able to release that memory. At least that's my understanding of DLLs.

                        L 1 Reply Last reply
                        0
                        • S Stefan_Lang

                          The problem with that is: 1. The caller may not know what method was used to allocate the memory (e. g. malloc or new), or if it was allocated at all, or instead just points to a static buffer! (Of course you could put that kind of information into the function documentation) 2. The OP put this function into a library interface. If bound statically, that would not pose a problem, but if bound dynamically, as a DLL, this DLL may use a separate heap - that means the caller may not even be able to release that memory. At least that's my understanding of DLLs.

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #17

                          Stefan_Lang wrote:

                          The caller may not know what method was used to allocate the memory (e. g. malloc or new), or if it was allocated at all, or instead just points to a static buffer!

                          Thats what documentation is for. This is actually quite common procedure, many APIs do this.

                          Stefan_Lang wrote:

                          The OP put this function into a library interface

                          Then the dll can expose a func that the caller can call to do the delete.

                          ============================== Nothing to say.

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups