c++ - 将非静态函数指针传递给另一个类?

标签 c++ winapi

我有两个类,Win32 和引擎。我试图将我的 WindowProc 函数从我的 Engine 类传递到 Win32 类。我知道 typedef WNDPROC 声明为:

typedef LRESULT(CALLBACK *WNDPROC)(HWND, UINT, WPARAM, LPARAM);

我的 Win32 header 声明为:

// Win32.h
#include <Windows.h>

class Win32
{
    public:
        Win32() {};
        ~Win32() {};

        void Initialize(WNDPROC);

    private:
        // Route messages to non static WindowProc that is declared in Engine class.
        static LRESULT CALLBACK MessageRouter(HWND, UINT, WPARAM, LPARAM);
};

我的引擎类声明为:

// Engine.h
#include "Win32.h"

class Engine
{
    public:
        Engine() {};
        ~Engine() {};

        void Initialize();

    private:
        LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);

        Win32* m_win32;
};


// Engine.cpp
#include "Engine.h"

void Engine::Initialize()
{
    m_win32 = new Win32;
    m_win32->Initialize(&WindowProc);  // How can I pass this function without making
                                       // it static or global.
}

我的 Win32 类已经有一个静态的 MessageRouter 给了 WNDCLASSEX。所以我的问题是,如何将 Engine::WindowProc 函数传递给 Win32 类而不声明它是静态的还是全局的?

最佳答案

您可以使用 std::functionstd::bind()(在 C++11 中),或 boost::function boost::bind()(在 C++03 中)。两者在功能上几乎相同,所以我将展示 std::bind() 的用法。

下面是如何根据 std::function 定义名为 WNDPROC_FXN 的类型别名:

typedef std::function<LRESULT CALLBACK (HWND, UINT, WPARAM, LPARAM)> WNDPROC_FXN;

这就是您在 Win32 类中使用它的方式:

class Win32
{
public:
    Win32() {};
    ~Win32() {};

    void Initialize(WNDPROC_FXN);
//                  ^^^^^^^^^^^

private:
    // Route messages to non static WindowProc that is declared in Engine class.
    static LRESULT CALLBACK MessageRouter(HWND, UINT, WPARAM, LPARAM);
};

这就是将成员函数绑定(bind)到 this 指针并将其传递给 Win32::Initialize() 的方式:

#include <functional>

// ...

void Engine::Initialize()
{
    using namespace std::placeholders;

    m_win32 = new Win32;
    m_win32->Initialize(std::bind(&Engine::WindowProc, this, _1, _2, _3 _4);
//                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

关于c++ - 将非静态函数指针传递给另一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17172697/

相关文章:

c# - 如何制作自动调节控件?

c++ - 智能指针的使用

c++ - DLL 注入(inject)有效,除非我在 Qt Creator 中编译它

c++ - 如何在同一个程序/函数中每次生成不同的随机数集?

c++ - 我可以从 Qt 的异常处理程序中发出信号吗?

c++ - 使用 C++ 递归扫描目录上的 ACL

c++ - Win32 API : GetLastError() with FormatMessage() prints a junk

windows - 定时器队列,立即终止定时器?

windows - 当新消息到达时,如何使任务栏像 Messenger 一样使我的应用程序闪烁?

c++ - 未将此指针设置为 const 的构造函数会导致未检测到的问题