Trampolining a non-static C++ member as a registered C callback - c++

I am writing a C++ freeGlut 3.0.0 application. I am having trouble registering a generic callback signature (hopefully a function pointer template argument) with a non static member function that matches the signatures of the declared free-glut callbacks.
To this end, with the help from this answer, I put together a live Coliru working example that demonstrates how to register a C++ non static method as a callback with a C application (in my case the freeGlut library). A better C interface would allow a caller to specify an optional void* user parameter which would typically be bound to this as described here.
FreeGlut does not allow provide a mechanism to do this in their callback registration API, so it seems that I need to use a trampolining technique that I am not very familiar with - especially when it comes to variadic parameter packs and such type_trait magic.
My cobbled together example uses one specific callback signature callback_t. The place where I need help is to allow a more generic callback templated type - perhaps the trampolining example live coliru demo could be adapted to make my example more generic but I am not sure how to get this working. I suspect I need to change the callback_t to somehow allow variadic arguments and a templated return type but I don't know how.
using callback_t = std::add_pointer<int(const char *, int)>::type;
using MyFTWFunction = std::function<void(unsigned char, int, int)>;
template <MyFTWFunction *callback>
class callback_binder {
public:
static void trampoline(unsigned char key, int x, int y) {
return (*callback)(key, x, y);
}
};
// This matches the signature of the callbacks in freeGlut
extern "C" {
// register the keyboard callback here
void glutKeyboardFunc(void(*callback)(unsigned char ch, int x, int y)) {
callback('S', 3, 4);
}
// register Reshape callback here
void glutReshapeFunc(void(*callback)(int, int)) {
callback(1, 2);
}
// register Display callback here
void glutDisplayFunc(void(*callback)(void)) {
callback();
}
}
I need help making it more generic such that I can also register other callbacks.

Related

How to use a C++ object's member function as a C-style callback?

I need to use an object instance function as a C-style callback without parameter, it can't be static because I need to access an instance variable and I can't modify the function using the callback.
The signature of the caller function is:
void attachInterrupt(uint32_t pin, void (*callback)(void), uint32_t mode);
Alas I can't use the capture list since it's a C-style only callback so the following won't work:
attachInterrupt(pin, [this]() { tracker(); }, mode);
I keep a static array of pointers to the object instances so I tried this:
static Actuator* actuator;
actuator = instance[index];
attachInterrupt(pin, [] { actuator->tracker(); }, mode);
The problem is that all the lambda functions share the same reference to the pointer stored in actuator but I need that each lambda function use it's specific pointer stored in instance[index].
The only way I had it to work properly yet is with a switch statement but I want to avoid hard coding as much as possible.
switch (index) {
case 0:
::attachInterrupt(pin, [] { instance[0]->tracker(); }, mode);
break;
case 1:
::attachInterrupt(pin, [] { instance[1]->tracker(); }, mode);
break;
...
}
There must be a way to pass a reference of a specific static element of the array to the lambda function without using the switch statement, how could I achieve that?
If you know the number of callbacks you want to register at compile time, you could create your callbacks as template function:
template <size_t i>
static void callback()
{
instance[i]->tracker();
}
Then you can use std::make_index_sequence and the unpacking syntax of variadic templates to register all at once:
template <size_t... ids>
void register_all_callbacks_impl(std::index_sequence<ids...>)
{
// the (f(), 0) syntax calls a void function f but returns an int 0
// with this trick you can leverage the unpacking syntax
// to call void functions in an array initialization
int dummy[] = { (attachInterrupt(pin, &callback<ids>, mode), 0)... };
(void)dummy; // omit "unused variable" warnings
}
constexpr size_t COUNT = ...;
void register_all_callbacks()
{
register_all_callbacks_impl(std::make_index_sequence<COUNT>());
}
All you need to do now is initialize your instance array with size COUNT and call register_all_callbacks().
Note: you need C++14 for make_index_sequence.
I would probably try something like
template<uint32_t pin, uint32_t mode> class callback
{
public:
static void attach() { ::attachInterrupt(pin, &callback::tracker, mode); }
private:
// Make specialization for each combination
static void tracker();
}
Then to register callback, you would do:
callback<5, 3>::attach();
callback<7, 2>::attach();
If the mode is a constant dependant on the pin number, then you would use a static member of the callback class and then initialize a specific value for each class type.
const uint32_t callback<7>::mode_for_this_pin = 3; // maybe constexpr instead?
But as the question does not contains much details, it is hard to give a good solution.
We assume that it is impossible to know the pin when the callback is called so that it is up to the client to associate a specific function to each pin.
Alternatively, you could also add a static std::function<void()> mfn member to the class and then initialize it like that:
callback<7, 3>::mfn = [] { your code here };
This could be useful if the callback to execute depend on some conditions.
There are no universal answer to your question as this is not directly supported by the language. The best solution depend on multiple factors that are not documented in your question.
Obviously if the function for a specific pin is always the same, you could easily have a function pin3_callback or pin3_mode2_callback and do whatever appropriate in the implementation.
Other points that are not specified in the question when initialization should be done and if some cleanup is required.
I know that under windows, some assembler code was used in the past to generate unique function for cases where it was not possible to provide user data to the callback.

Replace function-pointer implementation with std::function for using lambdas in PlayFab SDK

I'm currently trying to include the PlayFab C++ SDK into my app. This SDK is mainly for the game engine Cocos2d-x, but can be used for any C++ app basically.
It's just plain REST, hence you send requests to their servers and wait for the response. This would be perfect for using lambdas.
They declare this callback, which is called when a request is successful:
template<typename ResType> using ProcessApiCallback = void(*)(const ResType& result, void* userData);
Unfortunately, they're not using std::function, but a function pointer. This way one can not use lambdas that capture variables.
Hence, I thought I could simply replace this function pointer callback with an std::function callback like so:
template<typename ResType> using ProcessApiCallback = std::function<void(const ResType& result, void* userData)>;
Unfortunately, things are not that simply, as they stored the function pointers using ugly reinterpret_casts, here's an example (remove unnecessary parts to keep it short):
void PlayFabClientAPI::LoginWithAndroidDeviceID(
LoginWithAndroidDeviceIDRequest& request,
ProcessApiCallback<LoginResult> callback,
ErrorCallback errorCallback,
void* userData
)
{
// here they assign the callback to the httpRequest
httpRequest->SetResultCallback(reinterpret_cast<void*>(callback));
httpRequest->SetErrorCallback(errorCallback);
httpRequest->SetUserData(userData);
PlayFabSettings::httpRequester->AddRequest(httpRequest, OnLoginWithAndroidDeviceIDResult, userData);
}
Later on, when the request was successful, they do this:
if (request->GetResultCallback() != nullptr)
{
ProcessApiCallback<LoginResult> successCallback = reinterpret_cast<ProcessApiCallback<LoginResult>>(request->GetResultCallback());
successCallback(outResult, request->GetUserData());
}
The HttpRequest class has this field:
void* mResultCallback;
The problem is that I don't know how to store arbitrary std::function pointers in the HttpRequest class and then later cast them back. I tried many things, including also really ugly reinterpret_casting, but nothing did work.
I'm open to do any changes to their SDK. I also reported this as bad design and they agreed, but they don't have the time to improve it, but they will accept pull request if a good solution can be found.
The key item of information here is the userData pointer. It is supplied as part of the request, and it gets passed back to your callback function. This is an opaque pointer that the library pays no attention to, otherwise, except to forward it to your callback.
And this is what you will use, here.
This is a very common design pattern with generic service-oriented libraries that are written in C. Their APIs are often structured this way: they accept a request with an extra opaque pointer. They store this pointer, and they pass it back to the user-supplied callback, when the request completes.
The callback, then, uses it to associated any kind of additional metadata with the request.
This is a C++ library, but they chose to implement a C-style design pattern for library callbacks. That's unfortunate.
But, anyway, in your case you're going to dynamically allocate either your std::function, or some class's instance that contains your std::function, and any other data it needs, and pass the pointer to the dynamically-allocated structure to the request.
When your callback gets invoked, it simply needs to reinterpret_cast the opaque pointer to the dynamically-allocated type, copy its contents, delete it (in order to avoid memory leaks, of course), then proceed to use the copied contents as part of the callback action (whether it involves invoking the std::function, or something else, is immaterial).
Given that this is a C++ library you're using, and not a C library, it is unfortunate that they chose to implement this C-style opaque pointer pass-through design pattern. There are, of course, better ways to implement this in C++, but this is what you have to work with, so you'll have to deal with one ugly reintepret_cast. No way to avoid it.
To elaborate a bit on the answer by #SamVarshavchik here's a code snippet which should handle most of the process of generating a userData pointer and a "stateless" callback function taking the userData for you:
#include <memory>
#include <utility>
#include <type_traits>
#include <iostream>
template <typename T, typename... Args>
void c_callback_adaptor(Args... args, void* userData) {
auto callable = reinterpret_cast<T*>(userData);
(*callable)(args...);
}
template <typename Fn>
struct genCCallback_impl;
template <typename Res, typename... Args>
struct genCCallback_impl<Res(Args...)> {
template <typename T>
static std::pair<std::unique_ptr<std::decay_t<T>>,
Res (*)(Args..., void*)>
gen(T&& callable) {
return std::make_pair(
std::make_unique<std::decay_t<T>>(std::forward<T>(callable)),
c_callback_adaptor<std::decay_t<T>, Args...>);
}
};
template <typename Fn, typename T>
auto genCCallback(T&& callable) {
return genCCallback_impl<Fn>::gen(std::forward<T>(callable));
}
And a simple example of usage:
extern void registerCallback(void (*callbackFn)(int, int, void*), void* userData);
void test(int n) {
auto cCallback = genCCallback<void(int, int)>(
[n](int x, int y) {
std::cout << n << ' ' << x << ' ' << y << '\n';
});
registerCallback(cCallback.second, cCallback.first.get());
// for demo purposes make the allocated memory permanent
(void) cCallback.first.release();
}
(Of course, in actual code, you'd need to keep track of the std::unique_ptr until you're ready to unregister the callback.)
In answer to a comment: to break down what the templates are doing behind the scenes, suppose for illustration that the internal name of the lambda class is __lambda1. Then the test() function above generates code essentially equivalent to:
void c_callback_adaptor_lambda1(int x, int y, void* userData) {
auto callable = reinterpret_cast<__lambda1*>(userData);
(*callable)(x, y);
}
class __lambda1 {
public:
__lambda1(int n) { ... }
void operator()(int x, int y) const { std::cout << ...; }
...
private: ...
};
void test(int n) {
auto cCallback = std::make_pair(
std::make_unique<__lambda1>(n),
c_callback_adaptor_lambda1);
registerCallback(cCallback.second, cCallback.first.get());
(void) cCallback.first.release();
}
The PlayFab Cocos2dxSDK you have linked has since been upgraded to support lambda functions without modification to the SDK.
For Example:
PlayFabClientAPI::LoginWithEmailAddress(request,
[](const LoginResult& result, void* customData) { /* your login-success lambda here */ },
[](const PlayFabError& error, void* customData) { /* your error lambda here */ },
nullptr);

Create a function from another one

more than a general case, I have a very specific example in mind : in GSL (GNU Scientific Library), the main function type used (in order to perform integration, root finding,...) is gsl_function , which have an attribute function whose type is double(*)(double, void *)
Say I want to create a gsl_function from double a_squared(double a) {return a*a};. a__squared 's type is double(*)(double) I would like to create a convert function taking in argument (double(*)(double) f) and returning an object of type double(*)(double, void *) which would satisfy convert(f)(double a, NULL) == f(a)
But after some research, it seems like I can't define another function in my convert function. How to proceed ?
The need to pass a raw function pointer to the GSL API limits your options considerably - you can't use anything based on std::function because there's no way to obtain a function pointer from a std::function (and this rules out lambdas using captures, which would have offered a neat solution).
Given these constraints, here's a possible solution making use of a static wrapper class. You could just as well have put the contents of this class in a namespace, but using the class at least gives some semblance of encapsulation.
typedef double gsl_function_type(double, void*); // typedef to make things a bit more readable...
// static class to wrap single-parameter function in GSL-compatible interface
// this really just serves as a namespace - there are no non-static members,
// but using a class lets us keep the details private
class Convert
{
Convert() = delete; // don't allow construction of this class
// pointer to the function to be invoked
static double (*m_target)(double);
// this is the function we'll actually pass to GSL - it has the required signature
static double target(double x, void*) {
return m_target(x); // invoke the currently wrapped function
}
public:
// here's your "convert" function
static gsl_function_type* convert(double (*fn)(double)) {
m_target = fn;
return &target;
}
};
There's a live example here: http://coliru.stacked-crooked.com/a/8accb5db47a0c51d
You're trapped by gsl's (poor) design choice of using C (instead of C++) to provide a C-style function pointer. Thus, you cannot use (C++ style) function-objects (functor), but must provide the pointer to a real function and one cannot generate a function in the same way one can genarate functors.
(Not recommended) You can use a global variable to store the actual function (a_squared) and then define a particular gsl_function that actually calls that global variable:
// from some gsl header:
extern "C" {
typedef double gsl_function(double, void*);
// calls func(arg,data_passed_to_func)
double gsl_api_function(gsl_function*func, void*data_passed_to_func);
}
// in your source code
double(*target_func)(double); // global variable can be hidden in some namespace
extern "C" {
double funtion_calling_target(double, void*)
}
double funtion_calling_target(double arg, void*)
{
return target_func(arg);
}
bool test(double x, double(*func)(double))
{
target_func = func;
return x < gsl_api_function(function_calling_target,0);
}
(hiding target_func as static member of some class as in atkins's answer still requires a global variable). This works, but is poor, since 1) this mechanism requires a global variable and 2) only allows one target function to be used a any time (which may be hard to ensure).
(Recommended) However, you can define a special function that takes another function pointer as argument and passes it as data element. This was in fact the idea behind the design of gsl_function: the void* can point to any auxiliary data that may be required by the function. Such data can be another function.
// your header
extern "C" {
double function_of_double(double, void*);
}
inline double function_of_double(double arg, void*func)
{
typedef double(*func_of_double)(double);
return reinterpret_cast<func_of_double>(func)(arg);
}
// your application
bool test(double x, double(*func)(double))
{
return x < gsl_api_function(function_of_double, (void*)(func));
}
This does not require a global variable and works with as many different simultaneous functions as you want. Of course, here you are messing around with void*, the very thing that every sensible C++ programmer abhors, but then you're using a horrible C library which is based on void* manipulations.
Thought I would add my lambda-based attempts at this.
It works fine in principle:
// function we want to pass to GSL
double a_squared(double a) { return a*a; }
typedef double gsl_function_type(double, void*); // convenient typedef
// lambda wrapping a_squared in the required interface: we can pass f directly to GSL
gsl_function_type* f = [](double x, void*) { return a_squared(x); };
But we'd really like to write a method to apply this to any given function. Something like this:
gsl_function_type* convert(double (*fn)(double))
{
// The lambda has to capture the function pointer, fn.
return [fn](double x, void*) { return fn(x); };
}
However, the lambda now has to capture the pointer fn, because fn has automatic storage duration (in contrast to the static function a_squared in the first example). This doesn't compile because a lambda which uses a capture cannot be converted to a simple function pointer, as required by the return value of our function. In order to be able to return this lambda we'd have to use a std::function, but there's no way to get a raw function pointer from that, so it's no use here.
So the only way I've managed to get this to work is by using a preprocessor macro:
#define convert(f) [](double x, void*) { return f(x); }
This then lets me write something like this:
#include <iostream>
using namespace std;
typedef double gsl_function_type(double, void*); // convenient typedef
// example GSL function call
double some_gsl_function(gsl_function_type* function)
{
return function(5.0, nullptr);
}
// function we want to pass to GSL
double a_squared(double a) { return a*a; }
// macro to define an inline lambda wrapping f(double) in GSL signature
#define convert(f) [](double x, void*) { return f(x); }
int main()
{
cout << some_gsl_function(convert(a_squared)) << endl;
}
Personally, as much as I dislike using macros, I would prefer this over my other suggestion. In particular, it solves the problems #Walter pointed out with that idea.
Previous answers - including the accepted one - seem correct, but they are not general enough in case you need to convert other types of function to gsl_function (including member functions for example). So, let me add a more powerful alternative.
If you use the wrapper described here, then you can convert any C++ lambdas to gsl_functions in two simple lines
// Example
gsl_function_pp Fp([&](double x){return a_squared(x);});
gsl_function *F = static_cast<gsl_function*>(&Fp);
This solves any related conversion problems. You can also use std::bind and any std::functions.

Exposing a type-safe dynamic API with a shared library

I'm programming a plugin API interface for an application. The plugins are loaded as shared libraries at run time. They have access to the application API through an interface, such as the following:
class IPluginAPI
{
public:
virtual bool IsPluginsLoaded(void) = 0;
virtual bool IsHookingEnabled(void) = 0;
// And about 50 more methods
};
Plugins can request to 'listen' on certain events (such as MouseClick, MouseScroll etc.). These functions make up a total of >300 different events. Normally I would have done something like this:
extern "C" void SetEventHooks(APITable& table)
{
table.MouseClick = &PluginMouseClickEvent;
table.MouseMove = &PluginMouseMoveEvent;
}
Whereas the SetEventHooksfunction resides within the plugin library and is called from the application, and the plugins can listen to functions of interest by pointing to their functions. This is not the method I want to use, but I want to offer some kind of abstraction instead. This is what I had in mind:
// Interface IPluginAPI supplies a 'SetEventHook` method such as
void SetEventHook(HookID id, void * callback);
In this case HookID is a strong typed enum which contains all function IDs:
enum class HookID
{
MouseClick,
MouseMove,
// ...
};
So the plugin would use this function to listen to events:
pluginAPI->SetEventHook(ID::MouseClick, &myCallback);
The problem with this approach is that it is not type-safe and I cannot use templates directly (since this is done at runtime as libraries). I don't want to expose 300 different functions either for each event (e.gSetHookMouseMove(void (*)(int, int)) and so on). My last idea, is that the plugins have a utility template function which makes this type safe, but I'm not sure how to implement this in a simple way (and without boilerplate code):
template <typename T>
SetEventHook(HookID id, T callback)
{
if(typeof(T) == decltype(/* function type of the ID */))
gPluginAPI->SetEventHook(id, callback);
else static_assert("INVALID FUNCTION TYPE");
}
So to put it simple; how can I enable my plugins to hook to certain events in a dynamic type-safe way without exposing a complete function table and/or >300 methods for each event?
NOTE: I used function pointers for simplification, but I want to use std::function
As suggested by Kerrek, you can use traits policy to solve your problem. Basically as a part of public API you have to include structures defining callback type for each of your hook id.
// The default traits. If you don't want to have default traits comment body
// of this type out (including curly braces).
template <HookID id>
struct CallbackTraits
{
typedef void (*CallbackType)();
};
// Traits for MouseClick
template <>
struct CallbackTraits<HookID::MouseClick>
{
typedef void (*CallbackType)(int);
};
// Traits for MouseDoubleClick are the same
template <>
struct CallbackTraits<HookID::MouseDoubleClick> : CallbackTraits<HookID::MouseClick> {};
// Traits for MouseMove
template <>
struct CallbackTraits<HookID::MouseMove>
{
typedef void (*CallbackType)(int, int);
};
// actual hooking function
template <HookID id>
void SetEventHook(typename CallbackTraits<id>::CallbackType callback)
{
// do something with id and the callback
}
Now you can use this API following way:
// handlers prototypes
void MouseClicked(int button);
void MouseMoved(int x, int y);
void SomeEvent();
int main()
{
// compiles ok
SetEventHook<HookID::MouseClick>(MouseClicked);
SetEventHook<HookID::MouseMove>(MouseMoved);
// won't compile - function signature incompatible
SetEventHook<HookID::MouseDoubleClick>(MouseMoved);
// will compile if you left default traits body uncommented
SetEventHook<HookID::HookWithNoTraitsDefined>(SomeEvent);
return 0;
}
I've uploaded a working sample here.

Function pointer to class member function problems

First of all I have to admit that my programming skills are pretty limited and I took over a (really small) existing C++ OOP project where I try to push my own stuff in. Unfortunately I'm experiencing a problem which goes beyond my knowledge and I hope to find some help here. I'm working with a third party library (which cannot be changed) for grabbing images from a camera and will use some placeholder names here.
The third party library has a function "ThirdPartyGrab" to start a continuous live grab and takes a pointer to a function which will be called every time a new frame arrives. So in a normal C application it goes like this:
ThirdPartyGrab (HookFunction);
"HookFunction" needs to be declared as:
long _stdcall HookFunction (long, long, void*);
or "BUF_HOOK_FUNCTION_PTR" which is declared as
typedef long (_stdcall *HOOK_FUNCTION_PTR) (long, long, void*);
Now I have a C++ application and a class "MyFrameGrabber" which should encapsulate everything I do. So I put in the hook function as a private member like this:
long _stdcall HookFunction (long, long, void*);
Also there is a public void function "StartGrab" in my class which should start the Grab. Inside I try to call:
ThirdPartyGrab (..., HookFunction, ...);
which (not surprisingly) fails. It says that the function call to MyFrameGrabber::HookFunction misses the argument list and I should try to use &MyFrameGrabber::HookFunction to create a pointer instead. However passing "&MyFrameGrabber::HookFunction" instead results in another error that this cannot be converted to BUF_HOOK_FUNCTION_PTR.
After reading through the C++ FAQ function pointers I think I understand the problem but can't make up a solution. I tried to make the hook function static but this also results in a conversion error. I also thought of putting the hook function outside of the class but I need to use class functions inside the hook function. Is there another way or do I need to change my whole concept?
EDIT 14.01.08:
I tested the singleton workaround since I cannot change the third party library and the void pointer is only for data that is used inside the hook function. Unfortunately it didn't worked out of the box like I hoped.... I don't know if the static function needs to be in a separate class so I put it in my "MyFrameGrabber" class:
static MyFrameGrabber& instance()
{
static MyFrameGrabber _instance;
return _instance;
}
long Hook(long, long, void*); // Implementation is in a separate cpp file
In my cpp file I have the call_hook function:
long MFTYPE call_hook(long x, MIL_ID y, void MPTYPE *z)
{
return MyFrameGrabber::instance().Hook(x,y,z);
}
void
MyFrameGrabber::grab ()
{
ThirdPartyGrab(..., call_hook, ...);
}
But this gives me an error in static MatroxFrameGrabber _instance; that no matching standard constructor is found. That's correct because my MyFrameGrabber constructor looks like this:
MyFrameGrabber (void* x,
const std::string &y, int z,
std::string &zz);
I tried to put in an empty constructor MyFrameGrabber(); but this results in a linker error. Should I pass empty parameters to the MyFrameGrabber constructor in the singleton? Or do I need to have a separate Hook Class and if yes how could I access MyFrameGrabber functions? Thanks in advance.
SECOND EDIT 15.01.08:
I applied the changes and it compiles and links now. Unfortunately I cannot test this at runtime yet because it's a DLL and I have no Debug Caller Exe yet and there are other problems during initialization etc. I will mark the post as answer because I'm sure this is the right way to do this.
Your private member method has an implicit this pointer as first argument. If you write that out, it's obvious that the function signatures do not match.
You need to write a static member function, which can be passed as the callback-function to the library. The last argument to the HookFunction, a void*, looks to me very much like a cookie, where one can pass ones own pointer in.
So, all in all, it should be something like this:
class MyClass {
long MyCallback(long, long) {
// implement your callback code here
}
static long __stdcall ThirdPartyGrabCallback(long a, long b, void* self) {
return reinterpret_cast<MyClass*>(self)->MyCallback(a, b);
}
public:
void StartGrab() {
ThirdPartyGrab(..., &MyClass::ThirdPartyGrabCallback, ..., this, ...);
}
};
This of course only works if the void* argument is doing what I said. The position of the this in the ThirdPartyGrab() call should be easy to find when having the complete function signature including the parameter names available.
The reason "&MyFrameGrabber::HookFunction" cannot be converted to a BUF_HOOK_FUNCTION_PTR is that, being a member of the class, it has implicitly as first parameter the "this" pointer, thus you cannot convert a member function to a non-member function: the two signatures look the same but are actually different.
I would declare an interface, defining the function to call, have your class implement it and pass the object itself instead of the callback (you can think of an interface as the object-oriented replacement of a function pointer):
class IHookInterface{
public:
virtual long HookFunction(long, long, void*) = 0;
};
class HookClass : public IHookInterface{
public:
virtual long Hook(long, long, void*) {
// your code here...
}
};
// new definition:
ThirdPartyGrab (..., IHookInterface, ...);
EDIT - other possible solution in case you cannot modify the library: use a singleton rather than a static function.
class HookClass{
public:
static HookClass& instance(){
static HookClass _instance;
return _instance;
}
long Hook(long, long, void*) {
// your code here...
}
};
long call_hook(long x,long y,void * z){
return HookClass::instance().Hook(x,y,z);
}
SECOND EDIT: you might slightly modify the singleton class with an initialization method to call the constructor with the proper parameters, but maybe it is not more elegant than the following solution, which is simpler:
class HookClass{
public:
HookClass(string x,string y...){
}
long Hook(long, long, void*) {
// your code here...
}
};
static HookClass * hook_instance = 0;
long call_hook(long x,long y,void * z){
if (0 != hook_instance){
return hook_instance->Hook(x,y,z);
}
}
int main(){
hook_instance = new HookClass("x","y");
ThirdPartyGrab(..., call_hook, ...);
}