用法一:调用函数
函数指针是指向函数的指针变量。 因而“函数指针”本身首先应是指针变量,只不过该指针变量指向函数。这正如用指针变量可指向整型变量、字符型、数组一样,这里是指向函数。如前所述,C在编译时,每一个函数都有一个入口地址,该入口地址就是函数指针所指向的地址。有了指向函数的指针变量后,可用该指针变量调用函数,就如同用指针变量可引用其他类型变量一样,在这些概念上是一致的。函数指针有两个用途:调用函数和做函数的参数。
typedef int (*SERVER_PACKET_HANDLER)(CSession* session,char* packet); //定义一个返回int类型的函数指针,参数为(CSession* session,char* packet)
SERVER_PACKET_HANDLER handler; //声明变量handler
char buf[4]={0};
memcpy(buf,packet->RecvBuf,4);
int type = *(int*)buf;
handler = CServerPacketDispatcher::GetSingleton()->GetHandler(type); //赋值,将参数为(CSession* session,char* packet)的函数的首地址赋给变量handler
if(handler != NULL)
{
handler(session,packet); //调用函数
}
用法二:调用动态链接库
void CBCorpuscleSystemApp::UserLogin()
{
typedef int (*lpFun)(char *pUserName/*用与输出*/, CFont *pfont=NULL,int fontHeight=10);
HINSTANCE hDll; //DLL句柄
hDll = LoadLibrary("UserLogin.dll");
lpFun pShowDlg = (lpFun)GetProcAddress(hDll,"UserLoginShow");
char UserName[64];
user_level =pShowDlg(UserName,&framefont,11*(GetSystemMetrics( SM_CXSCREEN )/1024.0) );
m_strInspecDoctor=UserName;
FreeLibrary(hDll);
}
用法三:将函数指针传递给模板类
假设有一模板类:
template<class T>
class HandlerHash
{
public:
HandlerHash() {}
~HandlerHash() {}
public:
int Insert(int id,T handler);
T GetHandler(int id);
private:
map<int,T>m_handler_hash;
};
定义一个子类:
class CServerPacketDispatcher:public HandlerHash<SERVER_PACKET_HANDLER>