How to call Windows function pointers?

torhu no at spam.invalid
Sat Aug 16 20:32:48 PDT 2008


Benji Smith wrote:
[...]
>    extern(Windows) BOOL function(MEMORYSTATUSEX) fn;
> 
>    public void callWin32Function() {
>      auto lib = SharedLib.load(`c:\windows\system32\kernel32.dll`);
>      void* sym = lib.getSymbol("GlobalMemoryStatusEx");
>      fn = cast(BOOL function(MEMORYSTATUSEX)) sym;

Do this instead:
fn = cast(typeof(fn)) sym;


Below is a useful template if you have many functions.  It could be 
changed into a struct that saves the SharedLib object first, so you 
don't need to give it that for each function.  I'm not sure if the 
stringof trick will always work, though...

void bindFunc(alias funcPtr)(SharedLib lib)
{
	funcPtr = cast(typeof(funcPtr))lib.getSymbol(funcPtr.stringof.ptr);
}


Example usage:

extern(Windows) BOOL function(MEMORYSTATUSEX) GlobalMemoryStatusEx;

auto lib = SharedLib.load(`c:\windows\system32\kernel32.dll`);
bindFunc!(GlobalMemoryStatusEx)(lib);


Now you can call GlobalMemoryStatusEx.


More information about the Digitalmars-d-learn mailing list