public
Last active

Callback

  • Download Gist
gistfile1.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
#include <Windows.h>
 
namespace w32 { namespace tp {
 
class Hints;
class Queue;
 
// Dispatches calls to a function with a painful signature (see PTP_TIMER).
class Timer
{
/* class methods. */
private:
// allocate timer handle and register callback.
static ::PTP_TIMER setup (
::PTP_CALLBACK_ENVIRON queue,
::PTP_TIMER_CALLBACK callback,
void * context
);
 
/* nested types. */
public:
// compile-time binding for free function.
template<void(*F)(Hints&,void*)> struct function;
 
// compile-time binding for member function.
template<typename T, void(T::*M)(Hints&)> struct method;
 
/* data. */
private:
::PTP_TIMER myHandle;
 
/* constructors. */
public:
template<void(*F)(Hints&,void*)>
Timer ( Queue& queue, function<F> function, void * context=0 )
: myHandle(setup(queue.handle(), function, context))
{
}
 
template<typename T, void(T::*M)(Hints&)>
Timer ( Queue& queue, T& object, method<T,M> method )
: myHandle(setup(queue.handle(), method, &object))
{
}
 
// ...
};
 
template<void(*F)(Hints&,void*)>
struct Timer::function
{
// Return function with the proper signature that
// invokes the free function bound at compile-time.
operator ::PTP_TIMER_CALLBACK () const
{
return (&timer_callback);
}
 
private:
static void __stdcall timer_callback(
::PTP_CALLBACK_INSTANCE instance,
void * context,
::PTP_TIMER handle
)
{
F(Hints(instance), context);
}
};
 
template<typename T, void(T::*M)(Hints&)>
struct Timer::method
{
// Return function with the proper signature that
// casts the context pointer to 'T*' and invokes
// the member function bound at compile-time.
operator ::PTP_TIMER_CALLBACK () const
{
return (&timer_callback);
}
 
private:
static void __stdcall timer_callback(
::PTP_CALLBACK_INSTANCE instance,
void * context,
::PTP_TIMER handle
)
{
(static_cast<T*>(context)->*M)(Hints(instance));
}
};
 
} }
 
// ... USE AS FOLLOWS:
 
class Foo
{
public:
void bar ( w32::tp::Hints& );
};
 
using w32::tp::Timer;
Timer timer(queue, foo, Timer::method<Foo,&Foo::bar>());

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.