【问题标题】:Why is the result incorrect when assigning a string to const char * and then passing the const char * as a buffer (void*) to a function?为什么将字符串分配给 const char * 然后将 const char * 作为缓冲区 (void*) 传递给函数时结果不正确?
【发布时间】:2019-09-23 07:14:33
【问题描述】:

(我正在使用库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);

客户端上第二个和第三个代码 sn-ps 的输出是“ججججججججججج”。不是“Hello World”。

为什么?

【问题讨论】:

  • 我猜字符串的生命周期在你使用它之前就结束了,如果你使用MHD_RESPMEM_MUST_COPY而不是MHD_RESPMEM_PERSISTENT,这将正常工作。
  • @Hasturkun 哇,没想到,谢谢!
  • 我认为提及您使用的库可能会有所帮助,并澄清您描述的观察结果是否在调用函数时立即发生,或者这些是否是在输出之前完成的其他操作观察到。

标签: c++ string parameter-passing


【解决方案1】:

str 的生命周期在它被库使用之前就结束了。

在这种特定情况下,让 libmicrohttpd 复制缓冲区应该可以解决问题。

更具体地说,MHD_create_response_from_buffer 的模式参数需要设置为 MHD_RESPMEM_MUST_COPY,因为您的源缓冲区(字符串内部)的生命周期比函数返回的 MHD_Response 短。

【讨论】:

  • 这似乎是一个有效的解释。但是,只有结合您的评论才有意义。您能否相应地完成此答案?我也不是 100% 清楚:对于那些不了解这个库的人,MHD_create_response_from_buffer() 是否仅在稍后使用该字符串(即将提供的指针存储在响应对象中以供以后使用)?
  • @Christophe:我已经添加了细节。我不太了解 MHD(也不想深入研究),但 API 希望复制或获取提供的缓冲区的所有权(并且这些响应是异步使用的)。
猜你喜欢
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多