Introduction
Entrusted is a reference type in C #, similar to a function pointer in C / C . Unlike functional pointers, delegate is object-oriented, secure, and entrusting can reference static methods and instance methods, and function pointers can only reference static functions. The commission is mainly used for event handler and callback functions in .NET Framework.
A commission can be seen as a special class, so its definition can be placed in the same position like a conventional class. Like other classes, the commission must first define, then instantiate. Different from the class, instantiated entrustments do not have the corresponding terms (instantiated objects of the class), as a distinction we will instantiate the entrustment example.
Function pointer
A function is assigned to an entry address when compiling, which is called a function of the function, just as the pointer is the address of a variable.
There are many functions of the function pointer, one of the most common purposes is to pass the pointer as a parameter to other functions. We can refer to the example below to further understand the function of the function pointer as a parameter:
# include Objectively speaking, using function pointer as a function of its parameters If the function is directly called the function or directly put the function body of the called function in this main function. So why should I use a function pointer? Let's take a closer look that the main () function can find that the main () function calls the TEST function twice, the maximum minimum value is obtained before, and two sums of difference are obtained again. If we do not use a function pointer, do you use a Test function to complete this function with a method of calling a function directly in a Test function? Obviously, we must write two such TEST functions for main () function calls, although most code is still the same, just called the function name. The above is just a simple example. In the actual life, the main () function will call Test (), and each difference is only different, and may be the first call request to ask for two and With poor, the next time you ask for maximum and two sum, the third time, maybe a minimum and maximum, ...... If you don't need a function pointer, how many of these Test () functions we need to write ? Obviously, function pointers provide flexibility for our programming. In addition, some places must use a function pointer to complete a given task, especially asynchronous operation callbacks and other structures that require anonymous callbacks. In addition, the implementation of the thread, the processing of the event, is difficult to complete if the support of the function pointer is not completed. Type security It can be seen from the above introduction that the function pointer is still necessary, and the introduction above also indicates the necessity of delegate. So why don't I use a function pointer in C #, but to use the delegation? This involves another problem: C # is a type of security language. What is the type of security? The type of type herein refers to memory type security, that is, the type security code only accesss the memory location that is authorized to access. If the code accesses the memory at any offset, the offset exceeds the memory range of the public field belonging to the object, and it is not a type of secure code. Obviously the pointer does not belong to the type security code, which is why the C # uses a pointer must declare the unsafe. So what is the adverse consequence of type inactive code? I believe that friends who are interested in security technologies must be familiar with the buffer overflow problem. By the buffer overflow attacker can run illegal programs to get certain permissions to attack the system or run the malicious code hazard system, which is a very very common problem. So what is the relationship between the buffer overflow and the function pointer? In fact, the attacker is to change the value to the malicious code address by the buffer overflow change to the malicious code address. We can take a look at the code below: Void copy () {char buffer [128]; ........ Strcpy (buffer, getenv ("home")); // Home is the Home environment variable in the UNIX system ........ } In the above code, if the number of home environment variables is greater than 128, the buffer overflow will generate a buffer overflow, and if this buffer has another function returned, then this is that the address is possible to overwrite, and the address is overwritten. Characters may be the address of malicious code, and the attacker may have a successful attack! The above example is merely one of the pointer issues, in addition to this, may write data to an error address due to the wrong management address, resulting in a crash of the program; it is also possible to generate a floating pointer due to an improper assignment operation of the pointer; It is also possible to produce memory-proof, memory leaks, etc. It can be seen that the pointer is not type safe, and the function pointer is of course no exception, so there is no function pointer inside C #, and the pointer variable is not recommended. Delegate The previous description fully demonstrates the necessity of delegate, then let's talk about why the entrusted is safe. The delegation and pointer in C # are different. The pointer does not pass MSIL, but also the reasons why the pointer is unsafe. Of course, the pointer can improve the speed of the program, but not to deal with the memory, but Have this job to CLR to complete. The CLR cannot block the unsafe code to call the unsafe code into the unit (non-managed) code or perform malicious operations. However, when the code is safe, the CLR security enforcement mechanism ensures that the code does not access the native code unless it has access to the local code. Delegate to be derived from the base class System.deLegate, but the definition of the commission is not the same. Delegate definitions by keyword delegate: Public Delegate Int MyDelegate (int X, int y); The above code defines a new delegate, which can package any way to return to INT, with two int type parameters. Any method is whether the example method or a static method, as long as their signature (parameter type in a method) and the definition delegate are the same, they can be encapsulated into the delegate. This signature method is to ensure that the entrusted is one of the means of type security. Generate a delegate instance and a class instance (object) is similar, if we have the following methods: Public int SUB (int X, int y) { Return (x y); } We can use the following code to get a commission instance: MyDelegate Calculatin = New MyDelegate (SUB); Next we can use the Calculation to call the SUB method directly: Calculation (10, 3); Below we will use the entrustment to rewrite a program that is implemented in C #, how to implement the function of the function pointer by delegate: Using system; class mathclass {public static int max (int A, int b) {RETURN (A> B? A: B);} public static int min (int A, int b) {RETURN (a
We can also declare an array of entrustments, just like declaring an array of objects, use the entrustment array in the examples; a commission can also package multiple methods (multi-channel broadcast delegation, often combined with the event handler), as long as The signature of these methods is correct. The return value of multiple broadcast delegates is generally void because a delegate can only have a return value. If a return value does not encapsulates multiple methods without the VOID, it can only get the return value of the last package. This may be inconsistent with the user's original intention, and it will also bring inconvenience to management. If you want to return multiple values by delegate, it is best to use the entrustment array, allowing each delegate to encapsulate a method, each returns a value. event In C #, the most basic use of the commission is used for event processing. The event is the message sent by the object, in which the occurrence of signal notification operations, the event is that the event is a signal that requires a process in the program. The definition of the event is declared with keyword EVENT, but there must be a multi-channel broadcasted commission before declaring events: Public Delegate Void Calculate (INT X, INT Y); // The return value is the entrustment of VOID to automatically become a multi-channel broadcast commission; Public Event Calculate Oncalculate; As can be seen from the previously entrusted example and the above-mentioned statement, the statement of the event is just a keyword Event than the declaration of the entrustment instance. In fact, the event can be considered as a multi-channel broadcast customized by the event processing. Entrusted. Therefore, after the event is defined, we can achieve the process of the event or pass-= cancellation of the operation = adding method to the event, which is the same as the process of the delegate instance. Unlike the entrustment example, operators = for events are invalid, Oncalculate = new Calculate (SUB); // invalid Just because the above statement will delete all other ways from the oncalculate package, referring to the unique way to encapsulates this statement, and a scheduled can delete all other methods, which will cause confusion. Callback The callback function is the code that helps the non-host DLL function to complete the task in the hosted application. The call to the callback function will be passed from the hosted application, indirectly passed to the hosting implementation indirectly through a DLL function. In a variety of DLL functions called in the platform call, some functions require the correct operation of the callback function in the hosted code. About the callback function is just use to use the delegate, there is no more explanation here, and the specific implementation can be refer to the figure below: