Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9140795
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T09:33:47+00:00 2026-06-17T09:33:47+00:00

I need to pass a Lambda as callback (in particular for WinAPI). The idea

  • 0

I need to pass a Lambda as callback (in particular for WinAPI). The idea is the following:

  1. Store the lambda in a singleton class (every Lambda, also two identical ones, have different types) so it should be safe

    LambdaSingleton<Lambda_Type>::instance = l;

  2. Pass as callback the address of static method that invokes the lambda instance.

    template <
        typename Lambda,
        typename Callback_Signature_R,
        typename... Callback_Signature_Args>
    struct LambdaCallbackSupport{
    
        /**
        *   Callback method
        *
        *   @param  args
        *               The parameters to feed to the lambda
        *   @return 
        *               The return value of the execution of the lambda
        */
        static Callback_Signature_R __stdcall callback(Callback_Signature_Args... args){
            return LambdaSingleton<Lambda>::instance(args);
        }
    };
    

I already have a working class for extracting informations about functions at compile time es:

template<
    typename C,
    typename R,
    typename... Args>
struct Traits<R(__stdcall *)(Args...) const>{
      //various typedefs for R, tuple of args, arity etc..
};

So i would get something like this:

//Example lambda
int toBeCaptured = 8;
auto lambda =
    [&](std::string& str) -> size_t{
        return toBeCaptured + str.length();
    };

typedef decltype(lambda) Lambda;

//Expected callback signature
typedef size_t(__stdcall *CallbackSignature)(std::string&);

//Configure a callback support and pass its method
typedef Traits<CallbackSignature> callbackTraits;

typedef LambdaCallbackSupport<
    Lambda,
    callbackTraits::Result_Type,
    callbackTraits::Args_Tuple_Pack> CallbackSupportType;
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  //How to unpack the tuple without actually have the arguments??

//Store the lambda instance statically
Singleton<Lambda>::instance = lambda;

//Pass the callback
void* pFunc = &CallbackSupportType::callback;

//Simulate invocation of callback
std::string str("may work?");
size_t ret = (*pFunc)(str);

Since i need only to let the compiler generate a callback class specialization (and not actually invoke its method) how can i apply the iterative unpacking technique proposed in other questions on this site?

Thank you

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T09:33:48+00:00Added an answer on June 17, 2026 at 9:33 am

    As a general answer to your question (how to do tuple unpacking), parameter packs can only be generated implicitly in the context of template argument type deduction, so if you want to “unpack” a type tuple<T1, ..., Tn> into a sequence of types T1, ..., Tn you have to instantiate that tuple and supply that instance in input to some function template:

    template<typename... Ts>
    void unpack(tuple<Ts...> const&) // Now you have an argument pack...
    

    However, considering what you want to achieve (get a WinAPI callback from a lambda), I would not rely on tuples, and rather use a free function template. That can be done without introducing many levels of indirections and wrappers. Here is a possible simple solution:

    #include <type_traits>
    #include <memory>
    
    template<typename F>
    struct singleton
    {
        static void set_instance(F f) { instance.reset(new F(f)); }
        static std::unique_ptr<F> instance;
    };
    
    template<typename F>
    std::unique_ptr<F> singleton<F>::instance;
    
    template<typename F, typename... Ts>
    typename std::result_of<F(Ts...)>::type __stdcall lambda_caller(Ts... args)
    {
        if (singleton<F>::instance == nullptr)
        {
            // throw some exception...
        }
        else
        {
            return (*(singleton<F>::instance))(args...);
        }
    }
    

    This is the framework. And this is how you would use it:

    #include <iostream>
    
    int main()
    {
        //Example lambda
        int toBeCaptured = 8;
        auto lambda =
            [&](std::string& str) -> size_t{
                return toBeCaptured + str.length();
            };
    
        singleton<decltype(lambda)>::set_instance(lambda);
        size_t (__stdcall *pfn)(std::string&) = &lambda_caller<decltype(lambda)>;
    
        std::string str = "hello";
        int out = pfn(str);
        std::cout << out;
    
        return 0;
    }
    

    If you don’t mind macros and want to simplify that further for some usage patterns (like the one above), you can add a macro like this:

    #define get_api_callback(lambda) \
        &lambda_caller<decltype(lambda)>; singleton<decltype(lambda)>::set_instance(lambda);
    

    That would change your main() function into the following:

    #include <iostream>
    
    int main()
    {
        //Example lambda
        int toBeCaptured = 8;
        auto lambda =
            [&](std::string& str) -> size_t{
                return toBeCaptured + str.length();
            };
    
        // As simple as that...
        size_t (__stdcall *pfn)(std::string&) = get_api_callback(lambda);
    
        std::string str = "hello";
        int out = pfn(str);
        std::cout << out;
    
        return 0;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to pass in a where lambda expression that'll be used in a
I need to pass the lambda query as a parameter, the followings code is
Let's say I have two models, Book and Page: class Book(models.Model): pass class Page(models.Model):
I need pass a string array from AlarmReceiver.class to Notify.class but the string is
I need to pass an extra parameter :mobilejs => true from jQuery to a
I need to pass argument to JNLP dynamically for which I tried using a
I need to pass Cursor object to another activity, what is the best way
I need to pass a variable which is captured from client side via jquery
I need to pass a parameter from an EditText and when I click the
I need to pass a simple Javascript array to my wcf ajax webservice: var

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.