1

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

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

我的 Win32 标头声明为:

// 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 类被声明为:

// 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 类已经有一个提供给 WNDCLASSEX 的静态 MessageRouter。所以我的问题是,如何将 Engine::WindowProc 函数传递给 Win32 类而不声明它是静态的或全局的?

4

2 回答 2

1

为了完整起见,也有一种方法可以使用语言结构。此实现使用指向成员函数的指针:

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

class Engine;

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

        void Initialize(LRESULT(CALLBACK Engine::* function)(HWND, UINT, WPARAM, LPARAM));

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

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

        void Initialize();

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

        Win32* m_win32;
};

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

int main(void)
{
    Engine engine;

    engine.Initialize();

    return 0;
}
于 2013-06-18T15:40:18.097 回答
1

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

以下是如何定义一个名为WNDPROC_FXNbased on的类型别名std::function

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);
};

这就是您将成员函数绑定到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);
//                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
于 2013-06-18T15:32:22.560 回答