Delphi to write your first DLL file, very simple!

xiaoxiao2021-03-06  38

First, make your first one

DLL

Project

1.File-> Close All-> file-> new

Bamboo

DLL

Bamboo

Code: // Automatically generates the following library project2; // This has a paragraph nonsense. Uses sysutils, classes; {$ r * .res} begin end.

2. Add a FUNC to come in:

Code: library project2; uss sysutils, classes; function mymax (x, y: integer): integer; stdcall; begin if x> y; result: = x else result: = y; end; // Remember: library name size It doesn't matter, but the case of DLL-FUNC is related. // written in DLL-FUNC-NAME to Mymax and Mymax is different. If you write a wrong, the immediate // The result is that your AP you call this DLL can't be found. // The case of the parameter is not related. There is no need to be the same name. If the prototype is (x, y: integer) but write // is written (A, B: Integer), it is nothing. // Remember: Add a stdcall again. In the book, if you write the DLL with Delphi, and hope not only to // delphi-ap, you want to use BCB / VC-AP, then you'd better add a stdcall; instruction // parameter type: Delphi has Many of its own variable types, of course, is not the DLL you like //, the Native language of Windows / DLL should be C. So if you want to pass the parameters of the DLL, we // use it as much as possible. These both, the latter will have a lot of trouble. If you are not familiar with C, it doesn't matter. Let's talk about it later. {$ R * .RES} begin end.

3. Send these shared FUNCs to make the outside world are your delphi-ap ﹞ ﹞用: Light, your AP can't use this, you have to add an exports.

Code: {$ r * .res} exports mymax; begin end.

4. Ok, you can compile according to Ctrl-F9. Do not press F9 at this time. DLL is not EXE ┌ can not be executed separately, if you press F9, there will be ErrorMSG. At this time, if the DLL has error, please correct it. Press CTRL-F9 again. At this time, there may be Warning, don't close, study it, see it. Press CTRL-F9 again, "DONE, COMPILED". There will be a * .dll with a directory. Congratulations, I have already gone. Second, test: open a new application: 1. Add a TButton

Code: ShowMessage (INTTOSTR (MyMax (30, 50)));

2. Inform EXE to catch a FUNC

Code: // In Form, Interface, Var plus function mymax (x, y: integer): integer; stdcall; external 'mytestdll.dll'; // mytestdll.dll for your DLL project name // DLL Name sensation does not matter. But remember to add an Extension .dll. In Win95 or NT, // is not an extension, but these two OS may be less and less. To add Extension Europe. Yes, simple. Is it very simple? Friends who are familiar with Delphi can see that the above code and the general Delphi program are basically the same, but there is more stdcall parameters after the TestDll function and declare the TestDll function with the exports statement. As long as the above code is compiled, you can get a dynamic link library called Delphi.dll. Now let's take a look at what you need to pay attention to. First, the function or procedure written in the DLL must add the stdcall call parameters. This call parameter is FAR in the Delphi 1 or Delphi 2 environment. This parameter is changed from Delphi 3 for stdcall, and the purpose is to replace the optimized Register parameter in order to use standard Win32 parameter transfer technology. Forgot to use the stdcall parameter is a common error. This error does not affect the compilation and generation of the DLL, but a very serious error occurs when calling this DLL, resulting in the deadlock of the operating system. The reason is that the register parameter is the default parameter of Delphi.

Second, the written function and process should be declared using an Exports statement as an external function. As everyone see, the TestDLL function is declared as an external function. This can make this function to see the externally, the specific method is the "Quick View" feature to view the DLL file. (If there is no "quick view" option to be installed from the Windows CD.) The TestDll function appears in the Export Table column. Another very good reason is that if you don't declare this, the function we have written will not be called, this is everyone who is not willing to see.

Third, when using a long string type, the variable is referenced to ShareMem. The String type in Delphi is very powerful. We know that the normal string length is 256 characters, but the String type in Delphi can reach 2G by default. (Yes, you don't have a mistake, it is indeed two megabytes.) At this time, if you insist on using the string type parameter, the variable is even logging information, it is to reference the ShareMem unit, and must be the first reference. Being the first referenced unit after the Uses statement. Such examples: Uses ShareMem, Sysutils, Classes; there is a little, in your project file (* .dpr) instead of the unit file (* .pas), do the same job, this point of Delphi comes with help files Did not clear, causing a lot of misunderstandings. If you don't do this, you are very likely to pay the cost of the crash. Avoid using String types is to declare the parameters, variables of the String type as PCHAR or shortstring (eg S: String [10]) type. The same problem occurs when you use a dynamic array, the method of solving is the same as above. Chapter III Static call DLL TOP in Delphi

Calling a DLL is easier than writing a DLL. First, give you a static call method, will introduce the dynamic call method and make a comparison on both ways. Similarly, we first raised an example of static calls.

Unit unit1;

InterfaceUses Windows, Messages, Sysutils, Classes, Graphics, Controls, Forms, Dialogs, Stdctrls

TYPE TFORM1 = Class (TFORM) Edit1: Tedit; Button1: Tbutton; Procedure Button1Click (sender: TOBJECT); private {private declarations}

Var Form1: TFORM1;

IMPLEMENTATION

{$ R * .dfm}

// The following code is really handwritten for us.

Function TestDLL (i: integer): integer; stdcall; external 'delphi.dll';

Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT); begin edit1.text: = INTTOSTR (Testdll (1));

End.

In the above example, we placed a edit box (Edit) and a button (Button) on the form, and a little code was written to test our Delphi.dll we have just prepared. Everyone can see that our unique work is to put the test portion of the TestDll function in the Implementation, and specify the location of Delphi.dll with the External statement. (In this example, the calling program and Delphi.dll are in the same directory.) Is exciting that the TestDLL function we wrote quickly was quickly recognized by Delphi. You can do such an experiment: Enter "TestDLL (", very fast Delphi will use the fly-by prompt to prompt what you should enter, just as simple as we are using other functions defined in Delphi. Notes have the following some:

First, call the parameters with stdcall. As mentioned earlier, the STDCALL parameters should be used when the functions in the DLL are referenced, the causes are the same as those mentioned above.

Second, use the External statement to specify the path and name of the called DLL file. As everyone saw, we specify the name of the DLL file to be called in the External statement. There is no write path because the DLL file and the main program called it in the same directory. If the DLL file is in C: /, we can write the above reference statement as external 'c: /delphi.dll'. Note the suffix of the file. DLL must be written.

Third, the global variable cannot be called from the DLL. If we declare some global variables in the DLL, such as: Var S: byte. Thus, the global variables in the DLL can be used normally, but s cannot be used by calling programs, and both s cannot be passed to the calling program as global variables. However, the variable declared in the calling program can be passed to the DLL as a parameter.

Fourth, the DLL called the call must exist. This is very important. You must exist if you request the DLL file called when using a static call method and the function or process to be called. If you do not exist or specify the path and file name incorrect, the system will prompt "Outth" or "No * .dll file" or "No * .dll file" when running the primary program.

The fourth chapter is moving in Delphi DLL TOP

Dynamic call DLL is relatively complicated, but very flexible. In order to fully explain the problem, this time we will give an example of a DLL called by C . First, compile the following DLL source program in C .

#include

Extern "C" _Declspec (DLLEXPORT) INT WINAPI TESTC (INT I) {Return i;}

After compiling, generate a DLL file, here we call this file as cpp.dll, only one function TESTC returns an integer type in this DLL. For convenience, we still refer to the above call program, just replace 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'); {Loading DLL} if TH> 0 THEN TRY TP: = GetProcaddress (th, pchar ('testc')); if TP <> nil dam tf: = TintFunc (TP); Edit1.Text: = INTOSTR (TF (1 )); {Call TESTC function} END ELSE ShowMessage ('TestC function is not found "; Finally Freelibrary (TH); {Release DLL} end else showMessage (' cpp.dll did not find '); end;

Everyone has seen, this dynamic calling technology is complicated, but as long as the parameters are modified, if the DLL name in LoadLibrary ('cpp.dll') is "Delphi.dll ', the called DLL can be dynamically changed.

1. Define the type of function or process to be called. In the above code we defined a TintFunc type, which corresponds to the function TESTC we want to call. Do the same definition work in other calls. And also add the stdcall call parameters.

Second, release the called DLL. We use LoadLibrary dynamics to call a DLL, but remember to manually release the DLL with Freelibrary after use, otherwise the DLL will always use the memory until you exit Windows or shutdown.

Now let's evaluate the advantages and disadvantages of two ways to call DLL. The static method is simple, easy to master and generally a little faster, but also more secure and reliable; however, the static method cannot flexibly loading the DLL required for running at runtime, but load the specified DLL until the main program starts running The DLL is released at the end of the program, and the method can be used only if the compiler and the system (such as Delphi) can be used. The dynamic method solves the deficiencies in the static method. It can easily access the functions and processes in the DLL, even newly added functions or processes in some old version DLLs; but the dynamic method is difficult to fully master, because of different Functions or processes must define a lot of complicated types and call methods. For beginners, the author recommends that you use a static method to use a dynamic call method after you are skilled.

Chapter 5 Using DLL Practical Tips TOP

First, write skills. 1. In order to ensure the correctness of the DLL, it can be written as part of the ordinary application. After the debug is correct, then from the main program, compile into a DLL.

2, in order to ensure the versatility of the DLL, the name of the visual control should be deducted in the DLL you have written, such as the Edit1 name in Edit1.Text; or custom type non-Windows definition, such as some record.

3, for easy debugging, each function and process should be as short as possible, and cooperate with specific detailed comments.

4, you should use TRY-Finally to handle possible errors and exceptions, pay attention to the SYSUTILS unit.

5, as little as possible to reduce the size of the DLL, in particular not to reference the visualization unit, such as the Dialogs unit. For example, in general, we can not reference the classes unit, which can reduce the compiled DLL to approximately 16KB. Second, call the skill. 1. When using a static method, you can rename the called function or process. In the DLL example written in the C mentioned earlier, if the extern "C" statement is removed, C will compile some strange function names. The original TESTC function will be named @ Testc $ S and so on, this Because C uses C Name Mangling technology. This function name is illegal in Delphi, we can solve this problem this: Rewriting the reference function is Function Testc (i: integer): integer; stdcall; external 'cpp.dll'; name '@ Testc $ s; Name The role is rename it.

2, you can put the DLL we have written in the Windows directory or in the Windows / System directory. Doing so can write only the name of the DLL in the external statement or the log path in the LoadLibrary statement. But doing this is somewhat improper, there is a large number of important system DLLs in these two directory. If your DLL is renowned, the consequences are unimaginable, and your programming technology does not reach the DLL written by yourself. Step in the system directory!

Third, debugging skills. 1. We know that the DLL cannot run and single-step debugging when writing. There is a way, that is, set a host program in the Run | Parameters menu. Add a single step debugging, breakpoint observation, and running in the host program in the Host Application field of the local page.

2. Add a DLL version information. The release of version information is important for the DLL in the opening ceremony. If the version information is included, the size of the DLL adds 2KB. Increase this space is worth it. Unfortunately, if we use the Project | Options menu, the version of the Version option is not, this Delphi is not mentioned, and the scriptures have found that as long as you add a line of code. Such examples:

Library Delphi;

Uses sysutils, classes;

{$ R * .res} // note, the above line of code must be added to this location

Function TestDLL (I: Integer): Integer; Stdcall; Begin Result: = i;

Exports TestDLL;

Begin end.

3. In order to avoid the name of other DLLs, it is best to use characters and underscore mixing when the DLL written by yourself. Such as: JL_TRY16.DLL.

4, if you have compiled some DLLs in Delphi 1 or Delphi 2, your original DLL is 16-bit. As long as the source code is recompiled in the new Delphi 3 or Delphi 4 environment, you can get 32-bit DLL.

[Post ": In addition to the most commonly used methods described above, the DLL can also be used to make the resource carrier. For example, changing icons in Windows is the resources used by the DLL. In addition, proficient in the DLL design technology, there are many benefits to the use of more advanced OLE, COM, and ActiveX programming.

转载请注明原文地址:https://www.9cbs.com/read-77905.html

New Post(0)