Home >Backend Development >C++ >How to Pass Member Function Pointers to External Functions in C ?
Passing Member Function Pointers to External Functions
Passing member function pointers as arguments to external functions can be tricky, especially when dealing with class types. This question focuses on a specific scenario where a member function of a class needs to be passed to a function that expects a member function pointer.
To achieve this, the external function requires both a pointer to the object and a pointer to the member function. In the given code snippet, the external function MenuButton::SetButton() takes a pointer to the object as ButtonObj and a pointer to the member function as ButtonFunc.
The solution involves passing both the object pointer and the member function pointer to MenuButton::SetButton(). In the provided class testMenu, the constructor calls x.SetButton(...) and passes this as the object pointer and test2 as the member function pointer. This ensures that when the external function is called, it has access to both the object and its member function.
Here's the modified code:
testMenu::testMenu() :MenuScreen("testMenu") { x.SetButton(100,100,TEXT("buttonNormal.png"), TEXT("buttonHover.png"), TEXT("buttonPressed.png"), 100, 40, this, &testMenu::test2); draw = false; }
Within the external function MenuButton::SetButton(), the object pointer and the member function pointer can be used to invoke the member function using the syntax ((ButtonObj)->*(ButtonFunc))();.
The above is the detailed content of How to Pass Member Function Pointers to External Functions in C ?. For more information, please follow other related articles on the PHP Chinese website!