In-depth understanding of C/C ++ function pointers

Source: Internet
Author: User

Address: http://blog.sina.com.cn/u/1082089673
The use of function pointer Arrays
 

I encountered such a problem during the development of a software. The previous module sent binary data to me. The input parameter is char * buffer and int length, and buffer is the first data address, length indicates the length of the batch of data. The data is characterized by an indefinite length and type. The first byte (buffer [0]) identifies the data type, which is 256 (28) in total. My task must process each possible data type, and my module contains several functions, which must be processed similarly in each function. Write the following code as follows:

Void MyFuntion (char * buffer, int length)
{
_ Int8 nStreamType = buffer [0];

Switch (nStreamType)
{
Case 0:
Function1 ();
Break;
Case 1:
......
Case 255:
Function255 ();
Break;
}
}
If you write this method, you must make so many judgments in each of my functions. The code to be written must be very long, and each processing is performed, the correct processing function must be found after many judgments, and the code execution efficiency is not high. To solve the above problem, I thought of using the array of function pointers to solve this problem.

The concept of function pointer is mentioned in the classic tutorial of C language programming by Mr. Tan haoqiang. In most cases, we cannot use it and ignore its existence. The function name is actually a pointer pointing to the function's entry address, but it is different from common pointers such as int * and double *. Let's look at the following example to understand the concept of the function pointer:
Int funtion (int x, int y );
Void main (void)
{
Int (* fun) (int x, int y );
Int a = 10, B = 20;
Function (a, B );
Fun = function;
(* Fun) (a, B );
......
}
Statement 1 defines a function. The input value is two integer values, and the return value is also an integer value. (The input parameter and return value can be of any other data type ); statement 3 defines a function pointer. Unlike int * or double *, the function pointer must specify the input parameter at the same time, indicating that this is a function pointer, * fun must also be enclosed in a pair of parentheses. Statement 6 assigns a function pointer to funtion, provided that * the input parameters and return values of fun and function must be consistent. Statement 5 calls the function () directly, and Statement 7 calls the function pointer. The two are equivalent.

Of course, the advantages of function pointers cannot be seen from the above examples. The main purpose is to introduce the concept of function pointer arrays. We can see from the above example that since the function name can be saved through the function pointer, we can define an array to save several function names, which is the function pointer array. The prerequisite for correct use of the function pointer array is that these functions that need to be saved through the function pointer array must have the same input and output values.

In this way, the problems I face in my work can be solved as follows:

First, define 256 processing functions (and their implementations ).

Void funtion0 (void );
......
Void funtion255 (void );

Define the function pointer array and assign values to the array.
Void (* fun [2, 256]) (void );

Fun [0] = function0;
......
Fun [255] = function ();
Finally, the MyFunction () function can be modified as follows:

Void MyFuntion (char * buffer, int length)
{
_ Int8 nStreamType = buffer [0];
(* Fun [nStreamType]) ();
}

With only two lines of code, 256 case statements are completed, which reduces the coding workload and uses nStreamType as the array subscript to directly call function pointers, code execution efficiency is also higher than case statements. If this is done in multiple functions, the function pointer array can better reflect its advantages.
Function pointer and typedef
Usage of function pointers in C ++ (including the usage of typedef)
(1) simple function pointer application.
// Form 1: return type (* function name) (parameter table)
Char (* pFun) (int );
Char glFun (int a) {return ;}
Void main ()
{
PFun = glFun;
(* PFun) (2 );
}
The first row defines a pointer variable pFun. First, according to the "Form 1" mentioned above, we realize that it is a pointer to a function. This function parameter is of the int type, and the return value is of the char type. We cannot use this pointer only in the first sentence, because we have not assigned a value to it.
The second row defines a function glFun (). This function is a function that returns char with int as the parameter. We need to understand the function at the pointer level-the function name is actually a pointer, and the function name points to the first address of the function code in the memory.
Then there is the cute main () function. You should have understood its first sentence-it assigns the address of the function glFun to the variable pFun. In the second sentence of the main () function, "* pFun" is obviously the content of the address pointed to by pFun. Of course, the content of the function glFun () is taken out, and the given parameter is 2.
(2) typedef is more intuitive and convenient.
// Form 2: typedef return type (* New Type) (parameter table)
Typedef char (* PTRFUN) (int );
PTRFUN pFun;
Char glFun (int a) {return ;}
Void main ()
{
PFun = glFun;
(* PFun) (2 );
}
The function of typedef is to define a new type. The first sentence defines a PTRFUN type and defines this type as a pointer to a function. This function takes an int as a parameter and returns the char type. You can use PTRFUN like int or char.
The code in the second line defines the variable pFun using this new type. In this case, the variable can be used as in Form 1.
(3) Use function pointers in C ++ classes.
// Form 3: typedef return type (Class Name: * New Type) (parameter table)
Class CA
{
Public:
Char lcFun (int a) {return ;}
};
CA ca;
Typedef char (CA: * PTRFUN) (int );
PTRFUN pFun;
Void main ()
{
PFun = CA: lcFun;
Ca. (* pFun) (2 );
}
Here, "class restrictions" or "object" are added to the definition and use of pointers to indicate the class of the function to which the Pointer Points, the class object can also be obtained by using new. For example:
CA * pca = new CA;
Pca-> (* pFun) (2 );
Delete pca;
In addition, this class Object Pointer can be a member variable within the class, and you can even use this pointer. For example:
Class CA has a member variable PTRFUN m_pfun;
Void CA: lcFun2 ()
{
(This-> * m_pFun) (2 );
}
In a word, the class member function pointer must have a "-> *" or ". *" call.
 
When calling a dynamic library, you are used to use typedef to redefine the function address (function pointer) in the dynamic library function. For example, the dynamic library (test. dll) has the following function:
Int DoCase (int, long );

There are two methods to call a dynamic library:

1. Declare a pointer function variable that is consistent with the type in the dynamic library:

Int (* DOCASE) (int, long); // point to the DoCase function address in the dynamic library

HINSTANCE gLibMyDLL = NULL;

GLibMyDLL = LoadLibrary ("test. dll ");

If (gLibMyDLL! = NULL)

{

// Obtain the function address

DOCASE = (int (*) (int, long) GetProcAddress (gLibMyDLL, "DoCase ");

}

// Call a function

Int s = DOCASE (1,1000 );

2. Define a pointer function with typedef: typedef (* DOCASE) (int, long );

HINSTANCE gLibMyDLL = NULL;

DOCASE _ docase;

GLibMyDLL = LoadLibrary ("test. dll ");

If (gLibMyDLL! = NULL)

{

_ Docase = (DOCASE) GetProcAddress (gLibMyDll, "DoCase ");

}

// Call a function

Int s = _ docase (1,1000 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.