0

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 = LoadLibrary(szDll);

if (h)

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

}

return pfn ? pfn(psz) : 0;

}
1

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

Comments

0
*(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++.]

5 Comments

It is not equivalent. You need a lvalue (eg. a reference type) in the left hand side, hence the indirection.
@Alexandre, couldn't get your point. Isn't (FARPROC)pfn an lvalue ?
no it isn't. When you write (FARPROC)pfn, you cast pfn's value and it becomes a rvalue.
@Alexandre, if you are talking about strict aliasing rules, then may be you are right. However, I have seen such code in my old DSP project, which was written in C. That's why I mentioned about deprecation.
If you have int x; and then you do (unsigned)x = 1 then this won't do the trick. You need *(unsigned*)&x = 1 to do type punning. Here you have the same problem: you need the indirection to build a lvalue. Note that in C++ you'd use static_cast here instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.