(我正在使用库 libmicrohttpd )
像这样的 const char * 工作得很好:
const char *page = "Hello World";
MHD_create_response_from_buffer(strlen(page), (void*)page, MHD_RESPMEM_PERSISTENT);
但是给 const char * 赋值一个字符串会在客户端输出一个奇怪的字符串:
std::string str = "Hello World";
const char *page = str.c_str();
MHD_create_response_from_buffer(strlen(page), (void*)page, MHD_RESPMEM_PERSISTENT);
或:
std::string str = "Hello World";
MHD_create_response_from_buffer(strlen(page.c_str()), &page[0], MHD_RESPMEM_PERSISTENT);
第二个和第三个代码片段在客户端的输出是“♬♬♬♬gin”。不是“ Hello World ”。
为什么?
最佳答案
str
的生命周期在它被库使用之前就结束了。
在这种特定情况下,使 libmicrohttpd 复制缓冲区应该可以解决问题。
更具体地说,MHD_create_response_from_buffer
的模式参数需要设置为 MHD_RESPMEM_MUST_COPY
,因为您的源缓冲区(字符串内部)的生命周期比函数返回的 MHD_Response 短。
关于c++ - 为什么将字符串分配给 const char * 然后将 const char * 作为缓冲区 (void*) 传递给函数时结果不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55991856/