我有两个类,Win32和Engine。我正在尝试将我的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类已经有一个静态MessageRouter,它被赋予WNDCLASSEX。所以我的问题是,如何将Engine :: WindowProc函数传递给Win32类而不将其声明为静态或全局?
答案 0 :(得分:1)
您可以使用std::function
和std::bind()
(在C ++ 11中)或boost::function
boost::bind()
(在C ++ 03中)。这两者在功能上几乎相同,因此我将展示std::bind()
的使用。
以下是根据WNDPROC_FXN
定义名为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);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
答案 1 :(得分: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;
}