Use nested functions as callbacks with Windows API functions?

John Chapman johnch_atms at hotmail.com
Tue Oct 2 11:15:21 UTC 2018


On Monday, 1 October 2018 at 20:27:43 UTC, spikespaz wrote:
> Of course there is nothing wrong with defining each callback as 
> a separate function, but then comes the issue of naming them. I 
> also don't like the way it makes my code look.

I think the best you can do is something like this:

---
auto callback(T, string file = __FILE__, size_t line = 
__LINE__)(T handler) {
   import std.traits;

   __gshared T handler_;
   handler_ = handler;

   extern(Windows)
   ReturnType!T fn(Parameters!T args) {
     synchronized return handler_(args);
   }

   return &fn;
}

void main() {
   HWND[] list;
   EnumWindows((HWND hwnd, LPARAM lparam) {
     list ~= hwnd;
     return TRUE;
   }.callback(), 0);
   writeln(list);
}
---



More information about the Digitalmars-d-learn mailing list