C++ - Transforming C asynchronous function to C++ future

less than 1 minute read

C API definition to read data from a file in asynchronous way.

1
2
void async_read_completed_callback(void* pUserData, char cont* pBuffer, int size);
void async_read_data(char const* pFilePath, void(*callback)(void* pUserData, char cont* pBuffer, int size));

C++ implementation by using future

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void read_data_callback_wrapper(void* pUserData, char const* pBuffer, int size) {
    std::promise<std::vector<char>> promiseVar = std::promise<std::vector<char>> (reinterpret_cast<std::promise<std::vector<char>>*>(user_data));
    std::vector<char> data;
    for (int idx = 0; idx < size; ++idx) {
         data.push_back(pBuffer[idx]);
    }
    promiseVar.set_value(data);
}
std::future<std::vector<char>> read_data_in_cpp(char const* pPath) {
    std::unique_ptr<std::promise<std::vector<char>>> promiseVar =
        std::make_unique<std::promise<std::vector<char>>>();
    std::future<std::vector<char>> futureRes = promiseVar->get_future();
    async_read_data(pPath, reinterpret_cast<void*>(promiseVar.get()), read_data_callback_wrapper);
    promiseVar.release();
    return futureRes;
}