Skip to content

Instantly share code, notes, and snippets.

@skabbes
Created November 11, 2013 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skabbes/7409493 to your computer and use it in GitHub Desktop.
Save skabbes/7409493 to your computer and use it in GitHub Desktop.
How to allocate into a vector<char> in libuv?
uv_buf_t alloc_buffer(uv_handle_t * handle, size_t suggested_size) {
vector<char> * data = new vector<char>(suggested_size);
return uv_buf_init(data->data(), suggested_size);
}
void on_read(uv_stream_t* stream, ssize_t nread, uv_buf_t buf) {
vector<char> * data = reinterpret_cast<vector<char> * >(buf.__data);
// do something else
delete data;
}
@bnoordhuis
Copy link

You can set handle->data or embed the handle in another struct or class and use a container_of-like macro to look up the address of the embedder. (container_of only works with POC (Plain Old C) style classes though. The moment you start inheriting, you're in implementation-defined territory.)

@skabbes
Copy link
Author

skabbes commented Nov 11, 2013

The handle is the same across calls to on_read though right? so there's be no way to know which on_read applied to which on_alloc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment