Important: Please read the Qt Code of Conduct -

How would you guys connect C Library/Function (incl. Callback) to your c++ code?

  • Dear guys,

    this question is rather theoretic question but I have already encountered this problem.

    There are some C Libraries like CURL, OpenSSL, WolfSSL, aso, which have Functions which expect a Function pointer as Argument.

    Since you can't pass Member Function Pointers and you can't pass Lambdas with captures in it, how do you work around?

    as Example:

    SSL_CTX_set_cookie_verify_cb(ctx, &verify_cookie);

    this function accepts a callback Function pointer

    int(*)(SSL*,unsigned char*,unsigned int);

    In most curl functions you can work around by passing this pointer as void* userdata to a static or standalone function which forwards back to class. But in this example it is not possible. How do you implement C Functions in your C++ code?


  • Hi,

    The simplest method is to use a static function with the correct signature in a cpp class .

    here what i'm doing for two callbacks functions from the Mac Coreaudio midi API.

    static void  MIDINotifyProc(const MIDINotification *msg, void *refCon);
    static void  MIDIReadProc(const MIDIPacketList *pkList, void *refCon, void *con);

    You can implement a pure C function as well, but you may need to declare the function as extern "C" for correct linkage (not tested, hope i'm not wrong :-) )

Log in to reply