Skip to content

P3969 round-tripping data through void* for C APIs #175

@vasama

Description

@vasama

C APIs often provide a void* parameter for context. It is sometimes desirable to pass non-pointer context through such a parameter. This can be achieved using std::bit_cast. The resulting pointer value will never be used for any other purpose than to std::bit_cast back to the original type.

template<typename T, typename U>
struct pair {
    T t;
    U u;
};

extern "C"
void somelib_set_callback(void(* callback)(void* context), void* context);

void my_callback(void* context) {
  auto [x, y] = std::bit_cast<pair<int, bool>>(context);
  // ...
}

void my_setup(int x, bool y) {
  somelib_set_callback(my_callback, std::bit_cast<void*>(pair(x, y)));
}```

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs-rationaleA paper lacks discussion on design or other matters

    Projects

    Status

    Todo

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions