我在C ++类的C包装器中有以下代码。我需要从我的json :: value对象返回响应的字符串值。问题是,使用c_str()返回一个在函数末尾被销毁的指针。因此,我有以下可怕和不安全的代码: -
const char* const response_Json(CResponse *resp) {
using namespace myclient;
Response *t = (Response*)resp;
const web::json::value& json = t->Json(); // NOTE: Json() can ONLY be called ONCE
std::ostringstream stream;
stream << json; // REQUIRED to get raw JSON as text, as serialize(void) does NOT work
//t->Json().serialize(stream); // Doesn't work - blank result
std::string asstr = stream.str();
static const std::string& statref = stream.str(); // REQUIRED to ensure reference to string, and thus contained c_str, is not destroyed
static const char* pref = statref.c_str(); // REQUIRED so we have a local char pointer that is not temporary, and thus destroyed at function's exit
return pref;
}
我发现statref和pref都需要声明为static const,以便实际返回一个值,而不是挂起的指针(即整个对象图需要的静态const),但是我我不知道为什么。我原以为那个pref的那个就足够了。
我想删除所有静态变量,因为这个函数会被多次调用,也许并行调用。
我需要做的是返回C char *或其副本,以避免使用静态const。我一直在寻找几天,无法在任何地方找到答案。
我得出的结论是,我需要传入一个这个函数修改的char *,而不是返回。
答案 0 :(得分:2)
您需要将缓冲区传递给response_Json
函数,该函数应将字符串复制到调用者提供的缓冲区中。
基本上你需要这个:
void const response_Json(CResponse *resp, char *buffer) {
using namespace myclient;
Response *t = (Response*)resp;
const web::json::value& json = t->Json(); // NOTE: Json() can ONLY be called ONCE
std::ostringstream stream;
stream << json; // REQUIRED to get raw JSON as text, as serialize(void) does NOT work
//t->Json().serialize(stream); // Doesn't work - blank result
std::string asstr = stream.str();
strcpy(buffer, asstr.c_str);
}
为简单起见,此处没有进行缓冲区溢出检查。
也许在函数的json stuff部分仍有改进的空间。