Hands-on instruction Delphi: Write Your DLL file (2)

Source: Internet
Author: User

Static call of DLL top in Delphi

Calling a DLL is easier than writing a DLL. First, we will introduce static call methods. Later we will introduce dynamic call methods and compare them. Let's take a static call example first.

Unit Unit1;

Interface

Uses
Windows, Messages, SysUtils, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls;

Type
TForm1 = class (TForm)
Edit1: TEdit;
Button1: TButton;
Procedure Button1Click (Sender: TObject );
Private
{Private declarations}
Public
{Public declarations}
End;

Var
Form1: TForm1;

Implementation

{$ R *. DFM}

// The following code is the code we actually write.

Function TestDll (I: integer): integer; stdcall;
External 'delphi. dll ';

Procedure TForm1.Button1Click (Sender: TObject );
Begin
Edit1.text: = inttostr (testdll (1 ));
End;

End.

In the above example, we placed an edit box and a button on the form, and wrote a little code to test the Delphi. dll we just compiled. We can see that the only task we do is to place the description of the testdll function in implementation, and specify the location of Delphi. DLL using the external statement. (In this example, the calling program and Delphi. dll are in the same directory .) The excitement is that the testdll function we wrote was quickly recognized by Delphi. You can do this experiment: Enter "testdll (", and soon Delphi will use the fly-by prompt to prompt you what parameters should be entered, it is as simple as using other functions defined in Delphi. Note the following:
I. Use stdcall to call Parameters
As mentioned above, the stdcall parameter must be used to reference functions and procedures in DLL, for the same reason as previously mentioned.

2. Use the external statement to specify the path and name of the called DLL file
As you can see, we specify the name of the DLL file to be called in the external statement. There is no write path because the DLL file is in the same directory as the main program that calls it. If the DLL file is in C: ", we can write the above reference statement as external 'C:" delphi. dll '. Note that the file suffix. dll must be written.

3. global variables cannot be called from DLL
If we declare a global variable in the DLL, such as var s: byte. In this way, the global variable s in dll can be used normally, but s cannot be used by the calling program, and s cannot be passed to the calling program as a global variable. However, variables declared in the calling program can be passed to the DLL as parameters.

4. The called DLL must exist.
This is very important. When a static call method is used, the DLL file called and the function or process to be called must exist. If it does not exist or the specified path and file name are incorrect, the system will prompt "errors during program startup" or "cannot find *. dll file" and other running errors when running the main program.

Dynamic call of DLL top in Delphi

Dynamic calling of DLL is much more complicated, but flexible. To fully illustrate this problem, we will give an example of calling a DLL compiled by C ++. First, compile the following DLL source code in C ++.

# Include

Extern "C" _ declspec (dllexport)
Int WINAPI TestC (int I)
{
Return I;
}

After compilation, a DLL file is generated. Here we call this file Cpp. dll, which contains only one function TestC that returns an integer. For convenience, we still reference the above calling program, but replaced the statements in the original Button1Click process with the following code.

Procedure TForm1.Button1Click (Sender: TObject );
Type
TIntFunc = function (I: integer): integer; stdcall;
Var
Th: Thandle;
Tf: TIntFunc;
Tp: TFarProc;
Begin
Th: = LoadLibrary ('cpp. dll '); {load DLL}
If Th> 0 then
Try
Tp: = GetProcAddress (Th, PChar ('testc '));
If Tp <> nil
Then begin
Tf: = TIntFunc (Tp );
Edit1.Text: = IntToStr (Tf (1); {call the TestC function}
End
Else
ShowMessage ('testc function not found ');
Finally
FreeLibrary (Th); {release DLL}
End
Else
ShowMessage ('cpp. dll not found ');
End;

As you can see, this dynamic calling technology is complicated, but you only need to modify the parameters, such as modifying LoadLibrary ('cpp. dll ') is named 'delphi. dll 'to dynamically change the called DLL.

1. define the type of the function or process to be called
In the above Code, we define a TIntFunc type, which corresponds to the TestC function we will call. The same definition is required for other calls. You must also add the stdcall call parameter.

Ii. Release the called DLL
We use LoadLibrary to call a DLL dynamically, but remember to manually release it with FreeLibrary after use, otherwise, the DLL will occupy the memory until you exit Windows or shut down.

Now let's evaluate the advantages and disadvantages of the two methods for calling DLL. Static methods are easy to implement, easy to master, and generally a little faster, and more secure and reliable. However, static methods cannot flexibly unload the required DLL during running, instead, the specified DLL is loaded at the beginning of the main program until the end of the program. In addition, this method can only be used by the compiler and linker-based systems (such as Delphi. The dynamic method effectively solves the shortcomings in the static method, so that you can easily access the functions and processes in the DLL, and even some newly added functions or processes in the old version DLL; however, it is difficult to fully grasp the dynamic methods. Because different functions or processes need to define many complex types and call methods. For beginners, I suggest you use static methods and use dynamic calling methods after you become proficient.

Practical Tips for using DLL top

I. Writing Skills
1. To ensure the correctness of the DLL, You can first compile it into a part of a common application, debug it correctly, then separate it from the main program, and compile it into a DLL.

2. To ensure the versatility of the DLL, you should prevent the name of the visualization control from appearing in the DLL you have compiled, such as the Edit1 name in Edit1.Text or custom non-Windows-defined types, such as a record.

3. In order to facilitate debugging, each function and process should be as short and concise as possible, with detailed annotations.

4. try-finally should be used to handle possible errors and exceptions. Note that SysUtils unit should be referenced at this time.

5. Use as few reference units as possible to reduce the DLL size. In particular, do not reference visualization units, such as Dialogs units. For example, in general, we can not reference the Classes unit, which can reduce the size of the compiled DLL by about 16 kb.

Ii. Call skills
1. When using static methods, you can rename the called function or process. In the preceding DLL example written in C ++, if the extern "C" statement is removed, C ++ will compile some strange function names, the original TestC function will be named as @ TestC $ s and so on. This is because C ++ uses C ++ name mangling technology. This function name is invalid in Delphi. We can solve this problem as follows:
Rewrite the reference function

Function TestC (I: integer): integer; stdcall;
External 'cpp. dll '; name' @ TestC $ s ';

The role of name is rename.

2. You can put the compiled DLL in the Windows directory or the Windows "system directory. In this way, you can write only the DLL name in the external or LoadLibrary statement without writing the path. But there is something wrong with this. There are a lot of important system DLL under these two directories. If the DLL you have compiled is the same as them, the consequences are simply unimaginable, besides, your programming technology is not as good as putting your own DLL into the system directory!

Iii. debugging skills
1. We know that the DLL cannot be run or debugged in a single step during compiling. One way is to set a Host Program in the Run | parameters menu. You can add the Host program name to the Host Application column on the Local page for single-step debugging, breakpoint observation, and running.

2. Add the DLL version information. The version information mentioned in the opening remarks is very important for the DLL. if the version information is included, the DLL size will increase by 2 kb. It is worth adding such a space. Fortunately, we can't directly use the Version option in the Project | options menu, which is not mentioned in the Help File of Delphi. The author found that you only need to add a line of code. For example:

Library Delphi;

Uses
SysUtils,
Classes;

{$ R *. RES}
// Note that the above line of code must be added to this position

Function TestDll (I: integer): integer; stdcall;
Begin
Result: = I;
End;

Exports
TestDll;

Begin
End.

3. To avoid renaming a DLL with another DLL, it is best to use a mix of characters, numbers, and underscores when naming the DLL. For example, jl_try16.dll.

4. If you have already compiled some DLL files in Delphi 1 or Delphi 2, the original DLL files are 16-bit. You only need to re-compile the source code in the New Delphi 3 or Delphi 4 environment to get a 32-bit DLL.

[Postscript]:In addition to the most commonly used DLL method described above, DLL can also be used as a resource carrier. For example, changing the icon in Windows is the resource in the DLL used. In addition, mastering the DLL design technology is of great benefit to the use of more advanced OLE, COM, and ActiveX programming.

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.