C-callback to function template: explicitly instantiate template

后端 未结 3 379
温柔的废话
温柔的废话 2020-12-10 03:18

Premise

I’m using a C library (from C++) which provides the following interface:

void register_callback(void* f, void* data);
void invoke_callback(         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 04:06

    POSIX recommends the following way to cast between function pointer types and object pointer types (which is undefined in C99):

    typedef void function_type(void*);
    function_type *p_to_function = &my_callback;
    void* p_to_data = *(void**)&p_to_function;
    
    // Undefined:
    // void* p_to_data = (void*)p_to_function;
    

    Notice that in C++-land, this would perform a reinterpret_cast(&p_to_function) from function_type**. This is not undefined but instead implementation-defined, unlike reinterpret_cast(p_to_function). So it's probably your best bet to write C++-conformant code that relies on the implementation.

提交回复
热议问题