gpt4 book ai didi

c++ - libuv - 自由写入缓冲区

转载 作者:行者123 更新时间:2023-11-30 03:13:46 28 4
gpt4 key购买 nike

uv_write 的文档指出 [ 1 ]:

Note The memory pointed to by the buffers must remain valid until the callback gets called. This also holds for uv_write2().

因此可能需要为缓冲区的基数进行动态分配。调用函数可能如下所示:

void write_to_stream(uv_stream_t* stream) {   
uv_write_t* write_req = new uv_write_t;
uv_buf_t buf{};
buf.base = new char[1024];
buf.len = 1024;
// fill the buffer
uv_write(write_req, stream, buf, 1, on_write);
}

在这种情况下,由 new char[1024] 分配的内存需要有效,直到触发 on_write 回调。

查看回调的签名 void on_write(uv_write_t* req, int status) 如何释放这个内存并不明显,因为似乎没有办法从内部访问这个指针回调。

void on_write(uv_write_t* req, int status) {
// how to find the memory allocated for req's buffer?
delete[] ???;
}

一旦不再需要,释放该内存的预期方法是什么?

最佳答案

因为libuv 是一个c 库,它的结构应该是标准布局类型。因此,您可以将 uv_write_tuv_buf_t 包装在上下文结构中,然后再转换回上下文结构。请参阅以下示例:

struct write_context_t {
uv_write_t write_req;
uv_buf_t buf;
~write_context_t() {
delete[] buf.base;
}
}

void on_write(uv_write_t* req, int status) {
write_context_t* context = reinterpret_cast<write_context_t*>(req);
/* Do stuff ... */
delete context;
}

void write_to_stream(uv_stream_t* stream) {
write_context_t* write_req = new write_context_t;

/* fill your write_req and buf info here ... */

// initiate write
uv_write(&write_req.write_req, stream, write_req.buf, 1, on_write);
}

这是可行的,因为指向标准布局对象的第一个非静态数据成员的指针可以与指向该对象的指针相互转换。

关于c++ - libuv - 自由写入缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58461208/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com