Home >Backend Development >C++ >How to Pass Member Function Pointers to External Functions in C ?

How to Pass Member Function Pointers to External Functions in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-11-29 06:25:14772browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn