Use nested functions as callbacks with Windows API functions?

spikespaz spikespaz at outlook.com
Mon Oct 1 23:07:29 UTC 2018


On Monday, 1 October 2018 at 21:03:24 UTC, Boris-Barboris wrote:
> On Monday, 1 October 2018 at 20:27:43 UTC, spikespaz wrote:
>> I was hoping I could use something more akin to JavaScript's 
>> syntax: (void* hWnd, long) => {}.
>>
>> I tried this but I'm getting errors with the signature, it 
>> says the function is a delegate and apparently Windows API 
>> can't accept a delegate.
>
> You can make it a non-delegate by passing a pointer to hWndList 
> in lParams as it was supposed to by WinApi devs, instead of 
> zero, and not implicitly capturing stack pointer by referencing 
> hWndList directly from the body.
>
> https://run.dlang.io/is/t4k4Nc

The problem with the code you have is that the callback needs to 
be extern (Windows). I don't know how to do that with a "lambda".

===========================================

import core.sys.windows.windows: EnumWindows;
import std.stdio: writeln;

void main() {
     void*[] hWndList;

     EnumWindows((void* hWnd, void* lParam) nothrow {
         *(cast(void*[] *) lParam) ~= hWnd;
         return true;
     }, &hWndList);

     writeln(hWndList);
}

===========================================

source\cb.d(7): Error: function 
core.sys.windows.winuser.EnumWindows(extern (Windows) int 
function(void*, long) nothrow, long) is not callable using 
argument types (bool function(void* hWnd, void* lParam) pure 
nothrow @system, void*[]*)
source\cb.d(7):        cannot pass argument __lambda1 of type 
bool function(void* hWnd, void* lParam) pure
nothrow @system to parameter extern (Windows) int function(void*, 
long) nothrow


More information about the Digitalmars-d-learn mailing list