Function pointers for winapi functions (stdcall/cd

2019-04-06 16:39发布

Please could someone give me a few tips for creating function pointers for MS winapi functions? I'm trying to create a pointer for DefWindowProc (DefWindowProcA/DefWindowProcW) but getting this error:

LRESULT (*dwp)(HWND, UINT, WPARAM, LPARAM) = &DefWindowProc;

error C2440: 'initializing' : cannot convert from 
'LRESULT (__stdcall *)(HWND,UINT,WPARAM,LPARAM)' 
to 'LRESULT (__cdecl *)(HWND,UINT,WPARAM,LPARAM)'

I can't figure out what I need to use because I am not used to the MS ascii/wide macros. By the way, I'm creating a function pointer to make a quick hack, and unfortunately I don't have time to explain why - but regardless, I think this question will be helpful to people who need to create winapi function pointers.

Update:

This code works, but I'm worried that it is bad practice (and does not adhere to unicode/ascii compile options). Should I define two specifications?

LRESULT (__stdcall* dwp)(HWND, UINT, WPARAM, LPARAM) = &DefWindowProc;

Update 2:

This is nicer (thanks to nobugz):

WNDPROC dwp = DefWindowProc;

3条回答
beautiful°
2楼-- · 2019-04-06 16:49

This isn't the 'crazy' MS ascii/wide macro, you've just got 2 different function declarations.

If you decorate your internal function with "extern C" around it, you'll expose your function with the same calling type as the original and it'll compile.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-04-06 17:03

You lack __stdcall in your prototype. You need to have a matching calling convention apart from a matching prototype. WINAPI functions are all __stdcall, while the default for C++ is __cdecl.

Using extern "C" { code } is a viable alternative.

查看更多
Animai°情兽
4楼-- · 2019-04-06 17:08

Fix the calling convention mismatch like this:

LRESULT (__stdcall * dwp)(HWND, UINT, WPARAM, LPARAM) = DefWindowProc;

A typedef can make this more readable:

typedef LRESULT (__stdcall * WindowProcedure)(HWND, UINT, WPARAM, LPARAM);
...
WindowProcedure dwp = DefWindowProc;

But, <windows.h> already has a typedef for this, you might as well use it:

WNDPROC dwp = DefWindowProc;
查看更多
登录 后发表回答