microsoft / microsoft/wil

Lambda adapter for callback with context

Open
#143 12 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature-request
Dominant language
C++
Stars
3k
Forks
300
Avg merge
19h 12m
Merged PRs (30d)
1

Description

There's lots of APIs have callback with a context. For example EnumWindows, it has a lParam to be passed to the callback.

However, if we want to use C++ lambda with such function, we can't capture vars directly.
Instead, we have to do this:

int something_to_capture0 = 42;
int something_to_capture1 = 43;
int something_to_capture2 = 44;

struct {
	int* capture0;
	int* capture1;
	int* capture2;
} capture = { &something_to_capture0, &something_to_capture1, &something_to_capture2 };

EnumWindows([](HWND hWnd, LPARAM lParam) -> BOOL {
	auto _capture = reinterpret_cast<decltype(&capture)>(lParam);
	// Use captured vars here...
	return TRUE;
}, reinterpret_cast<LPARAM>(&capture));

So is there a "lambda adapter" class, which makes things like this?

int something_to_capture0 = 42;
int something_to_capture1 = 43;
int something_to_capture2 = 44;

wil::lambda_adapter<WNDENUMPROC> adapter{ [&](HWND hWnd) -> BOOL {
	// Use captured vars here...
	return TRUE;
} };
EnumWindows(adapter.func_ptr(), adapter.context());

Edit: I just found that PTP_WORK_CALLBACK has context on the second parameter, so the above code should be changed to:

wil::lambda_adapter<WNDENUMPROC, 2>

The 2 indicates the second parameter of WNDENUMPROC is the context parameter.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the issue's EnumWindows/WNDENUMPROC example and compare it with PTP_WORK_CALLBACK, focusing on how each callback receives its context parameter. The work is done when a lambda adapter supports captured callbacks and exposes the callback pointer and context in the requested form, including selecting the context parameter position.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.