How DLLs are copied every hour when Delphi is installed. Creation of that variant of dynamic libraries (DLL) in Delphi. Singing DLL functions review

Golovna / Contacts

DLL- Dynamic Link Library or a library that dynamically connects, as it allows you to freeze one and the same functions in different programs. It’s true to get a handful, more importantly, that once a library has been written, it can be written in rich programs. In today's lesson, we learn to practice dll and, of course, create them!
Well, let's do it!

For the cob, let's make our Persha Dynamic Link Library! Virushaemo in Delphi And it’s immediately available in the menu File -> New -> Other.
Before us is the axis of the same in the end:

Selected from the Dynamic-Link Library list (for versions of younger 2009 Delphi item is called DLL Wizard).

As a result, we have less than a window with a code, respect the form we don’t have here!
Now naytsіkavіshe is repairing. Let's write our first procedures at the library.

library Project2;
// You, singly, already remembered that the program was replaced
//When the dll is created, the word library is called.
// What does the library mean.
uses
Sysutils, dialogs,
classes; // Respect! Don't forget to specify the modules,
// otherwise the code will not be processed

($R*.res)
(QIU CHASTIN HAS THE DLL CODE)

First ProcedureCall; stdcall; export;
//Stdcall - Which operator's parameters are placed on the stack
// left to right, and reversed on the standard value
//Export from the principle can be omitted, vicariously for clarification
//export procedure and function.

Begin
ShowMessage(" My first procedure in dll");

end;

DoubleProcedureCall; stdcall; export;
Begin
ShowMessage(" My friend procedure");
//Click on the screen
end;

Exports FirstCall, DoubleCall;
//The list of exported elements is stored in Exports.
// How to import as a program.

begin
end.

On tsomu mi, we still sho zupinimsya because for a simple butt, which will be sufficient. At once we save our project, especially I save it under the name Project2.dll and press the CTRL+F9 key combination to compile the library. Papa, where did you save the dpr file is guilty of the file appears extension dll, tsya i є our library is well created. I have it called Project2.dll

Now let's deal with the cycle of procedures of the library. We create a new program behind the standard scheme. Before us is nothing extraordinary, just a form. Take the new addendum to the Yakus folder. І in the qiu w folder I will copy it dll library. Tobto. in this butt Project2.dll

Now you have to choose how to call the functions of the library. We use two methods and vikliku.

Method #1
Might be the simplest method of recalling procedures that are found in the library.
It is ideal for a worker with only one library.

Well, let's go...
After the implementation keyword, the next code is written:

First ProcedureCall; stdcall; external "Project2.dll";
// Replace Project2.dll may be the name of the library

DoubleProcedureCall; stdcall; external "Project2.dll";

Here, as you already sing-songly guessed, we remind the program to name our procedures and say that the stench is in dll library in my opinion with the name of Project2.dll

Now, in order to call these procedures, we need only to insert their names in a place in the code, which we can immediately name. We throw 2 Button components on the form from the Standard tab and create on the skin sampler under OnClick

OnClick of the first button:


Begin
first call;
end;

OnClick another button:


Begin
double call; // I'm a procedure, like being in a dll
end;

From i all!

Method #2:
Folding is lower first, but it has its pluses, and it’s more heady, which is ideal for plugins.
For zastosuvannya given method, we are deafened by a sprat of global changes:

Var
LibHandle: HModule; //Send to the library module
FirstCall: procedure; stdcall;
//Names of our procedures that are in the library.

DoubleCall: procedure; stdcall;

Then, after the implementation keyword, we will write a procedure to take over our library:

Load ProcedureMyLibrary(FileName: String);
Begin
LibHandle := LoadLibrary(PWideChar(FileName));
//Get the library!
// Respect! PChar for versions lower than 2009 Delphi
If LibHandle = 0 then begin
MessageBox(0,"",0,0);
exit;
end;
FirstCall:= GetProcAddress(LibHandle,"FirstCall");
//Otrimuёm pokazhchik on the object
// The first parameter sent to the library module
//2nd parameter of object name in dll

DoubleCall:= GetProcAddress(LibHandle,"DoubleCall");
If @FirstCall = nil then begin

MessageBox(0," Impossible to take over the library",0,0);
exit;
end;
If @DoubleCall = nil then begin
// Revisiting the presence of this function in the library.
MessageBox(0," Impossible to take over the library",0,0);
exit;
end; end;

If something is created on the form, a sample of the OnCreate pod, in which, for the help of a well-created procedure, our library

Procedure TForm1.FormCreate(Sender: TObject);
Begin
LoadMyLibrary("Project2.dll");
end;

Now again, in order to retrieve the necessary procedures from our library, we need only insert their names in a place of the code. For this, we can throw 2 components of the Button on the form from the Standard tab and create it on the skin sampler under OnClick

OnClick of the first button:

Procedure TForm1.Button1Click(Sender: TObject);
Begin
first call; // I'm a procedure, like being in a dll
end;

OnClick another button:

Procedure TForm1.Button2Click(Sender: TObject);
Begin
double call; // I'm a procedure, like being in a dll
end;

Well, we are creating a copy of the OnDestroy on the form, in a kind of vivantage dll library from memory

Procedure TForm1.FormDestroy(Sender: TObject);
Begin
FreeLibrary(LibHandle);
//Looking at the memory library.
end;

From i all! Another way to write a cumbersome, but also a plus in the clarified object, which is collected in the library.

P.S. Do you want to decide ahead of time on the site and take fresh Video lessons, Audio podcasts, articles on Delphi.
Take part in competitions and step by step join our team?!
Subscribe directly to the free multimedia subscription to the site
There are already over 3500 of us!

Variant DLL in Delphi
  • DLL concept
  • Delphi DLL creation (export)
  • Delphi DLL wiki (import)
  • DLL that hacks VCL objects for work with data
  • Blame situations in DLL
  • DLL concept

Let's figure out the programming process in DOS. The transformation of the output text of the program into machine code, including two processes - compilation and linking. At the linking process, the editor of the links that composing Okremі modules programs by placing the code of the program as an open function and procedures, and the new code. You prepared one program in this way, another, a third ... I scraped the code of the quiet functions themselves, placing them in the program again.

Program1 Program2: : MyFunc(:) MyFunc(:) : : function code MyFunc function code MyFunc other function code other function code

The richly tasked middleware has such a pіdkhіd bіv less reckless, oskіlki it's obvious that the number of these functions themselves is majestic, vidpovіdalnyh for promalovuvannya elementіv іnterfejsі koristuvach's interface, for access to system resources and so on. duplicated b povnistyu at all addenda, which would lead to a swedish use of the most expensive resource - operational memory. The concept of dynamic linking has been propagated on UNIX-like platforms as the culmination of the problem, just like Vinyl (Fig. 2).

But why do Dynamic Link Library (DLL) look like great add-ons? To understand this, it is necessary to clarify the understanding of the task (task), the instance (copy) of the program (instance) and the module (module).

When you run a number of examples of one program, Windows zavantazhu in operational memory just one copy of the code and resources - the add-on module, creating a list of okremyh segments of data, a stack and lines of support (div. fig. 3), the skins of which are a set of tasks, in rozumіnі Windows. The program copy is the context in which the program module is located.

DLL - library is also a module. It will be stored in memory in a single instance and replace the code segment of that resource, as well as the data segment (div. Fig. 4).

DLL - Library Functions placed in a DLL are placed in the context of the program, which is called out by the stack. Ale t і nіkії ї vykoristovuyut segment danih scho nabіbrіtetsі, not kopiї program.

By virtue of such an organization, the DLL can save memory for the account that everything running programs hack one DLL module, not including all of them standard functions to the warehouse of their modules.

Often, as a DLL, there are just sets of functions that are combined for the same or other logical signs, similar to the way modules are conceptually planned (for a sense unit) in Pascal. The difference lies in the fact that functions from Pascal modules are linked statically - at the linking stage, and functions from DLLs are linked dynamically, that is, at run-time.

Delphi DLL creation (export)

To program the Delphi DLL, you need a series key words that ruled the syntax. Golovna - Delphi's DLL is such a project itself as a program.

Let's take a look at the DLL template:


The project file for such a template can be MYDLL.DPR.

Unfortunately, the Delphi IDE does not automatically generate a program project, so you have to prepare the DLL project manually. In Delphi 2.0, the opacity has been removed.

Like in the program, in the DLL є split uses. The initial part is not obov'yazkovaya. In the distribution of exports, the functions are re-arranged, access to which is to be blamed for vykonuvatisya іz zvnіshnіh dаdatkіv.

Exporting functions (and procedures) can be done in a number of ways:

  • by number (index)
  • by name

There is a different syntax in the following way:


Since Windows understands the "resident functions" of a DLL, so that these functions, which are known in memory for a long time, have a DLL base in memory, Delphi has tools for organizing this kind of export:


then the indexing of the functions that are exported will be broken by Delphi automatically, and such an export will be considered as an export by name, which is sorted by the function's name. However, voiced imported functions in the program may be affected by voiceless functions in the DLL. As for directives, which are already superimposed on functions, which are imported, then we will talk about them below.

Delphi DLL wiki (import)

For the organization of import, tobto. accessing functions, exporting DLLs, and ex-porting, Delphi provides standard costs.

For more applications, your program should indicate the functions that are imported from the DLL in this order:


This method is called static import.

As you could remember, the extension of the file, which to avenge the DLL, is not indicated - for the promotion, the *.DLL and *.EXE files are tossed about. If so, you should be aware that the file can be expanded further (for example, like COMPLIB.DCL in Delphi), or that you need to dynamically designate DLLs and import functions (for example, your program works with different graphic formats and for skin z them іsnuє okrema DLL.)?

To solve such problems, you can go directly to the Windows API, calling dynamic import like this:


uses WinTypes, WinProcs, ...; type TMyProc = procedure ; var Handle: THandle; MyImportProc: TMyProc; begin Handle:= LoadLibrary("MYDLL"); if Handle >= 32 then (if begin@MyImportProc:= GetProcAddress(Handle, "MYEXPORTPROC"); if MyImportProc nil then ... (using imported procedure) end; FreeLibrary(Handle); end;

Syntax diagrams for export/import deafening, DLL exit point change, and other applications. 21 Days".

If you don’t talk about the code that is generated by the compiler (there are more optimizations at the same time), then all syntax rules have been lost the same as in Borland Pascal 7.0

DLL that hacks VCL objects for work with data

When you create your own dynamic library, you can link functions from other DLLs. An example of such a DLL is supplied by Delphi (X: DELPHI DEMOS BDEDLL). Tsya DLL to replace the form, which displays data from tables and victories for access to it, VCL objects (TTable, TDBGrid, TSession), yak, in their own line, call BDE functions. How to yell at the comments to the bottom of my head, for such a DLL there is an obmezhennya: її cannot single-hourly win a dekіlka zavdan. Note that the Session object, which is created automatically when the DB module is connected, is initialized for the module, not for the task. If you try to grab a DLL with another program, winkle pardon. For pobebіgannya one-hour zavantazhennu DLL kіlkoma zavdannym need to zdіysnit deakі dії. In addition, there is a procedure for checking which DLLs are currently selected for other tasks.

Blame situations in DLL

The faulty situation in the DLL, created in Delphi, was brought before the faulty situation in all programs, so the situation was not generalized in the middle of the DLL. To that it is necessary to transfer all possible negativity at the time of the development of the DLL. You can recommend to rotate the result of the selected function, which is being imported, in order to look at the row or the number i, if necessary, re-calculate the culprit situation in the program.


function MyFunc: string; begin try (Clear function code) except on EResult: Exception do Result:=Format(DllErrorViewingTable, ) else Result:= Format(DllErrorViewingTable, ["Unknown error"]); end; end;

Program code:


StrResult:= MyFunc; if StrResult "" then raise Exception.Create(StrResult);

Stattya Variant DLL in Delphi distributed File system DLL and PlugIns can be used for Delphi and FreePascal retailers.

Abbreviation DLL means "a library that moves dynamically". Dll in Delphi tse file, what to avenge the necessary work computer software procedures and functions, with which the program stops at the stage of vikonannya.

It would be better if all the necessary subprograms can be described in the program type, for which it is necessary to create additional dll file that zadnuvatisya with him for an hour of vikonannya? Robe for more gnuchkost created programs. Over time, some data processing algorithms may change. If the programs will have processing procedures, you will have to recompile, and again transfer the file to the replacements. Transfer a small dll-file, which can be done with less than a few procedures, it is much simpler and run in automatic mode.

In addition, the robot library dll zovsіm not lie down in the language of the program, on which it will be created. Therefore, the creation of a dll for our program can be entrusted to third-party retailers, without thinking about the programming language, which stinks like. All the same, obviously, richly hasten the creation and transfer of the finished project to the deputies

DLL creation

Creation of dll in Delphi not more folding Add-on module. Type the command File -> New -> -> Other... At the dialog box that appears, select the DLL Wisard icon. As a result, Delphi will create a DLL library project:

library project1;

( Important note about DLL memory management: ShareMem must be the
first unit in your library "s USES clause AND your project" s (select
Project-View Source) USES clause if your DLL exports any procedures or
functions that pass strings are parameters or result functions. This
applies to all strings passed to and from your DLL - even those that
are nested in records and classes. ShareMem is the interface unit to
the BORLNDMM.DLL shared memory manager, which must be deployed along
with your DLL. In order to highlight BORLNDMM.DLL, pass string information
PChar or ShortString parameters. )

uses
sysutils,
classes;

($R*.res)

begin
end
.

Choose a name for the new dll library and save it in an okrem folder by typing the command file -> Save as... The paps have 4 files, there will be no middle dll-file. Sounds simple text files, what to do with the description of the project To create the sub-bag file of the dll library, it is necessary to compile the project. Wick the team project -> Compile Project. As a result, a dll-file will appear in our folder, and the main program will be loaded.

The library is still empty.

...now in the editing stage...



Entry

At the link with the turbulent development of programming technologies, more and more people are struggling with the problem of increasing the possibilities of their programs. This article is dedicated to the power itself, and to itself - the programming of the DLL from Borland Delphi. In addition, the shards of my torknemosya nourishment are good vikoristannya DLL, then it is important to import functions from other people's DLLs (including system ones, such as WinAPI).

DLL Stuck Areas

Otzhe, now we need DLL libraries and de stinks vikoristovuyutsya?

Okremі libraries mіstya korisnі for programmers additional functions. For example, functions for working in rows, or folding libraries for transforming images. Resource Treasures DLLs can be used as program functions, and various resources - icons, little ones, row arrays, menus, etc. Support Libraries As an example, you can add libraries of such packages, such as: DirectX, ICQAPI (API for ICQ), OpenGL also. Parts of the program For example, from the DLL you can save the program windows (form) too. Plugins Plugins are additions to programs that expand their capabilities. For example, in these articles, we can look at the theory of the creation of a plug-in for the program. The resource DLL (Dynamic Link Library) can be shared as often as possible by programs or processes (so-called sharing - a resource that is shared)

A short description of the functions and applications for robotic DLL

So, how do you accept that function? Let's take a look at two methods of importing functions from the library:

1 way Binding DLL to the program.

The simplest and easiest method for finding functions that are imported from a DLL. However (and for the sake of care) this method may be even more vagomous - like a library, like a wizard program, if it is not found, then the program simply does not start, seeing a pardon and reminding about those that the DLL resource was not found. And search the library to know: for streaming catalog, for software catalog, for WINDOWS\SYSTEM catalog, etc. Otzhe, for the cob - the form of which I will accept:


FunctionName (or ProcedureName) - the name of the function (or procedure), as it will be featured in your program; Par1, Par2, ... names of parameters in the function of the procedure; Par1Type, Par2Type, ... type of parameters in the function of the procedure (for example, Integer); ReturnType value type to rotate (function only); stdcall directive, which is exactly the responsibility of zbіgatisya z vikoristovuvanoy in the DLL itself; external "DLLNAME.DLL" directive that specifies the name of an existing DLL, in which case a function or procedure will be imported (in to this particular type- DLLNAME.DLL); name "FunctionName" ("ProcedureName") directive that specifies exactly the name of the function in the DLL itself. This is a neobov'yazkova directive, as it allows you to win in the program function, which I can name, in vіdmіnnu vіd іtіnnoї (yak i won't have the library); index FunctionIndex (ProcedureIndex) directive that specifies the ordinal number of a function or procedure in a DLL. Tse also neobov'yazkova directive.

This is a richly folded, ale and elegant method. Vіn concessions to the first method. The only thing that is unacceptable is the code that is necessary for the implementation of this acceptance, and the complexity of the fact that the function that is imported from the DLL is only available once the DLL is captured and known in memory ... so far - short description wicking cims using the WinAPI function method:

LoadLibrary(LibFileName: PChar) grabs the specified LibFileName library from memory. On successful completion, the function rotates the (THandle) DLL handle to memory. GetProcAddress(Module: THandle; ProcName: PChar) reads the address of the exported library function. Upon successful completion of the function, rotate the handle (TFarProc) of the function to the DLL captures. FreeLibrary(LibModule: THandle) work with a non-dead LibModule and let me remember it. The next step is to indicate that after the function procedures of the library are no longer available.

Practice that butt

Well, now the hour has come to bring a couple of examples of the most varied methods and approaches:

Example 1. Linking DLL to the program


Now the same, but in a different way - with dynamic interests:


Note:

Sliding to match the string type in library functions, because when yoga vikoristannі іsnuyut problems z "rozpodіl memory". You can read the report about it (true, English) in the empty text of the DLL project that Delphi is creating (File -> New -> DLL). So, quickly convert PChar, and then convert it to the string function StrPas.

And now let's take a look at the DLL itself:

Case 3. Reference to the MYDLL.DPR project


Placement in DLL resources and forms

DLL can be placed as functions, and cursors, little ones, icons, menus, text lines. We won’t be snarling on what we are. I would rather respect that the resource needs to capture the DLL, that buv, having removed the descriptor, - capture the resource itself with a similar function (LoadIcon, LoadCursor, etc.). For whom have distributed more than a little bit of the placement in the DLL libraries of the vicon programs (these forms are in Delphi).

For whom you need to create a new DLL and add a new form to it (File -> New -> DLL, and then - File -> New Form). Dalі, like the form is a dialog window (modal form (bsDialog)), then add it to the DLL come function(let's say the form is called Form1, that class is TForm1):

Example 4. Placement of forms at the DLL


In order to add a non-modal form to the DLL, it is necessary to add two functions - open and close forms. Whenever you need to change the DLL, remember the form handle.

Creation of plugins

Here we look at the plug-ins in detail, because Pointing it out will help you to easily get to the left side of the DLL programming. I’m guessing that the plugin is an addition to the program that expands its capabilities. In this case, the program itself can obov'yazkovo transfer the presence of such additions and allow them to vikonuvat their confession.

Tobto, for example, to create a plugin before graphics editor, after having converted the image, you will need to transfer at least two functions in the plugin (i, double-click on the functions in the program) - a function that turned b im'ya plug-in (i/or io type), to add this plugin to menu (or in the toolbar), plus main function- transmission and reception of the image. Tobto. The program searches for the plug-in from the beginning, then, for the skin found, it calls the function from the strictly named names (for example, GetPluginName) and adds the required item from the menu, then, as a matter of fact, by selecting this item - calling the function to a friend, as if transferring 'I'm a file, what to avenge the image), and this function, in its own way, converts the image and rotates it in a new look (otherwise, it's a file with a new image). Axis and the whole essence of the plugin...

Epilog

In this article, the main aspects of the selection of DLL libraries from Borland Delphi are shown. If you have food - send it to me by E-mail:

At the middle Delphi programming transfer to the library for the swedish creation of DLL libraries.

Let's create a library for singing, to avenge the function

GetArea(a, b, c: REAL): REAL.

With this function, the two sides of the tricutnik are served at the entrance. The function rotates the area of ​​a given tricot:

p:=(a+b+c)/2;

Result:=SQRT(p*(p-a)*(p-b)*(p-c))

Start Delphi, but the distance was unconventional. Select menu item FileNewOther, at the end, what was written on the bookmark Newclick on the icon DLL Wizard. ( algorithm to deposit in version)

At whom the DLL-library preparation file is created. Vіn is already similar to the greatest module (unit)Delphi, only depends on the operatorLibrary. Save the project for the sake of it, as in the future we will take the DLL-library, let's say,GetA. nameGetAreait is impossible to win - it is already occupied by them functions.

Now after the operatorUSESwe write the text of our function, but with some changes in the title:

FUNCTION GetArea(a, b, c:REAL):REAL;export;

The EXPORT keyword indicates that this function is exported and will be visible from the existing programs.

After the text of the function is ascribed

GetArea;

In the EXPORTS statement, all procedures and functions are redeemed, as they are exported from the library. This is a kind of catalog of our library.

It is impossible to launch the library on the vikonannya, її you can only compil it. For which one we can select the menu item Project → Build. Once everything has been spawned correctly, a file named geta.dll will be created on the streaming directory disk. This is our library.

Respectful respect Note: Useful subtlety when passing procedures and functions that are in the library, parameters of the STRING type.

In order to be able to pass parameters to the STRING type, in the USES statements and libraries, and the programs that call it, write the connection of the ShareMem module, dragging the language so that the module is the first in the list. Moreover, at the same time, the library will have to add the file borlndmm.dll (included in the Delphi delivery). It's easy to escape this situation: follow for the parameters of the text type to select the ShortString data type (the main string, or up to 255 characters) and PChar (the indicator for the text string).

Viklik dll

Explain two ways to call procedures and functions from a DLL. In the first place, we are far behind, at the stage of developing the program, we know that we will connect the DLL to it (mostly we ourselves and create the DLL). In another way, we connect to a fairly large library, including "foreign".

Static call

For the implementation of the first method, called static calls, create a new default program, place three input fields LabeledEdit1…LabeledEdit3 on the form, a button and a Tlabel component. After the IMPLEMENTATION statement, add a line to ensure the import of the GetArea function from the geta.dll library:

Function GetArea(a, b, c: real): REAL; FAR; EXTERNAL "Geta";

The word EXTERNAL indicates those that the body of the function can be found in the library and assigned names, and the word FAR specifies the zastosuvannya "double" chotiribayte address, which is necessary, the screens of the program, which are called, to be found on the same side, library - in English. Obviously, the file geta.dll needs to be placed in the same directory where all the files of the streaming program are located.

The push button pusher needs to create an array and pass it to the library function, and display the result on the screen:

procedure TForm1.Button1Click(Sender: TObject);

© 2022 androidas.ru - All about Android