开发者

Function Pointer basic question

I have a basic question on function pointer. In the below code snippet, how do I read this " *(FARPROC*)&pfn ="?

IFastString *CallCreateFastString(const char *psz) {

static IFastString * (*pfn)(const char *) = 0;

if (!pfn) {

const TCHAR szDll[] = _TEXT("FastString.DLL");

const char szFn[] = "CreateFastString";

HINSTANCE h = 开发者_StackOverflow中文版LoadLibrary(szDll);

if (h)

*(FARPROC*)&pfn = GetProcAddress(h, szFn);

}

return pfn ? pfn(psz) : 0;

}


This isn't really about function pointers, but about casting in general.

Suppose pfn is of type T. Then &pfn is of type T*. This gets cast to FARPROC* by the cast expression (the stuff in the parentheses). Finally, this gets dereferenced, yielding a FARPROC&.

All in all this just means you're treating pfn as if it were of type FARPROC and assign a value to it.

Here's a generic example:

S make_an_S();

T x;
T * const px = &x;
S * const py = (S*)px;
*py = make_an_S();  // same as *(S*)&x = make_an_S();


*(FARPROC*)&pfn = GetProcAddress(h, szFn);

is equivalent to,

(FARPROC)pfn = GetProcAddress(h, szFn);

So, pfn is a function pointer which is type casted to FARPROC to store the address received from GetProcAddress(h, szFn).

[Note: I am not sure, if this kind of typecasting is deprecated in C++.]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜