Return dynamically allocated memory from C++ to C

前端 未结 10 2354
粉色の甜心
粉色の甜心 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:34

    After the function is called, you will want the caller to be responsible for the memory of the string (and especially for de-allocating it). Unless you want to use static variables, but there be dragons! The best way to do this cleanly is to have the caller do the allocation of the memory in the first place:

    void foo() {
      char result[64];
      GetString(result, sizeof(result));
      puts(result);
    }

    and then GetString should look like this:

    int GetString(char * dst, size_t len) {
      std::stringstream ss;
      ss << "The random number is: " << rand();
      strncpy(ss.str().c_str(), dst, len);
    }

    Passing the maximum buffer length and using strncpy() will avoid accidentally overwriting the buffer.

提交回复
热议问题