今天在閱讀libcurl的源碼的時候,發現裡邊定義函數指針的方法,與平時自己所用方式有所不同。詳細分析了一下。
libcurl的代碼中,定義了一組發送數據的函數指針。如下所示:
//代碼目錄: lib/urldata.h
struct connectdata {
......
Curl_send *send[2];
......
};
其中,Curl_send定義如下:
//代碼目錄: lib/urldata.h
/* return the count of bytes sent, or -1 on error */
typedef ssize_t (Curl_send)(struct connectdata *conn, /* connection data */
int sockindex, /* socketindex */
const void *buf, /* data to write */
size_t len, /* max amount to write */
CURLcode *err); /* error to return */
//定義一個函數指針,所指向函數接收一個整形參數,並返回整形值。 typedef int (*pFunc)(int);但是,curl_send的定義中,並沒有帶上指針符號。在查閱一些資料後,發現這樣的定義方法也是可以的。
於是,寫了下面的程序驗證了一下。
#ifdef __cplusplus #include如果將上面程序保存為C程序文件(.c),進行編譯,得到下面運行結果:#else #include #endif int testFunc(int para) { #ifdef __cplusplus std::cout << C++ parameter is: << para << std::endl; #else printf(C parameter is: %d , para); #endif return 0; } int main() { typedef int (pTestFunc)(int); pTestFunc *pFunc = testFunc; //方式1:ok· pFunc(1111); //方式2:ok (*pFunc)(2222); //方式3:ok pTestFunc *pFunc2 = &testFunc; //方式4:ok pFunc2(3333); return 0; }
當然,我們也可以采用傳統的函數指針聲明方式,如下程序所示:
int main()
{
typedef int (*pTestFunc)(int);
pTestFunc pFunc = testFunc; //方式5:ok
pFunc(1111); //方式6:ok
(*pFunc)(2222); //方式7:ok
pTestFunc pFunc2 = &testFunc; //方式8:ok
pFunc2(3333);
return 0;
}
運行結果與前面所述完全相同。