Home >Backend Development >C++ >Can C Class Member Functions Be Used as C Callbacks?
Using a C Class Member Function as a C Callback Function
Problem:
When attempting to register a C class member function as a callback function for a C library, the compiler throws an error indicating that the function's type does not match the expected signature.
Questions:
Answer:
1. Using a Static Member Function:
Yes, it is possible to register a C class member function as a callback function, but it must be a static member function. Static member functions do not have an implicit first parameter of type class A*, so their signature matches the expected callback signature. For example:
class A { public: static int e(int *k, int *j) { return 0; } }; int main() { register_with_library(A::e); return 0; }
2. Alternative Approaches:
Alternatively, you can use one of the following approaches:
void e_wrapper(int *k, int *j) { A().e(k, j); }
int (*ptr)(int *, int *) = &A::e; register_with_library(ptr);
The above is the detailed content of Can C Class Member Functions Be Used as C Callbacks?. For more information, please follow other related articles on the PHP Chinese website!