How to initialize function pointers painlessly?

I want to load Win32 API functions using Runtime.loadLibrary and GetProcAddress(...) . Using mixin :

 template GetProcA(alias func, alias name_in_DLL) { const char[] GetProcA = func ~ ` = cast(typeof(`~func~`)) GetProcAddress(hModule,"`~name_in_DLL~`");`; } ... static extern (Windows) Object function (HWND hWnd, int nIndex) GetWindowLong; static extern (Windows) Object function (HWND hWnd, int nIndex, Object dwNewLong) SetWindowLong; 

I can create an instance (in the class constructor) as follows:

 mixin GetProcA!("SetWindowLong", "SetWindowLongA"); 

but if you use it again for another function:

 mixin GetProcA!("GetWindowLong", "GetWindowLongA"); 

the compiler complains:

 mixin GetProcA!("GetWindowLong","GetWindowLongA") GetProcA isn't a template... 

I do not see the point: if the first instance created GetProcA , and I can not use it again, since it helps me?

+4
source share
2 answers

Judging by your code, you want a mixin expression , not a template Mixin :

 string GetProcA(string func, string name_in_dll) { return func ~ ` = cast(typeof(` ~ func ~ `)) ` ~ `GetProcAddress(hModule,"` ~ name_in_dll ~ `");`; } mixin(GetProcA("SetWindowLong", "SetWindowLongA")); mixin(GetProcA("GetWindowLong", "GetWindowLongA")); 

In fact, you don’t even need a mix. Enough internal template function:

 hModule = ...; void GetProcA(T)(ref T func, string name_in_all) { func = cast(typeof(func)) GetProcAddress(hModule, toStringz(name_in_all)); } GetProcA(SetWindowLong, "SetWindowLongA"); GetProcA(GetWindowLong, "GetWindowLongA"); 
+6
source

I think KennyTM is true. However, for completeness, you can use the same mixin more than once if you name them. Find "MixinIdentifier" here .

+3
source

Source: https://habr.com/ru/post/1390256/


All Articles