Return dynamically allocated memory from C++ to C

前端 未结 10 2358
粉色の甜心
粉色の甜心 2021-01-01 07:10

I have a dll that must be useable from C etc, so I cant use string objects etc as a normal would, but I\'m not sure on how to do this safely..

const char *Ge         


        
10条回答
  •  醉酒成梦
    2021-01-01 07:41

    If thread-safety is not important,

    const char *GetString()
    {
        static char *out;
        std::stringstream ss;
        ss << "The random number is: " << rand();
        delete[] out;
        char *out = new char[ss.str().size()];
        strcpy(ss.str().c_str(), out);
        return out;//is out ever deleted?
    }
    

    Then the function can take over the responsibility of deallocating the string.

    If thread-safety is important,

    Then the best method is to pass it in as an argument, as in,

    void GetString(char *out, int maxlen);
    

    I observe this is what happens when the old non thread-safe APIs are changed to thread-safe.

提交回复
热议问题