Delphi Foundation III Writing and invoking DLL files

Source: Internet
Author: User
Tags define function

Delphi Writing and invoking DLL file

The executable file for Windows can be divided into two forms of program and Dynamic Connection library (DLLs). General program operation is used. EXE file, but the application can sometimes call functions stored in the DLL.

In the following cases, it is reasonable to call the DLL:

1) different programs use the same DLL, so that only need to load the DLL in memory once, saving the memory overhead.

2) When certain content needs to be upgraded, it is possible to use a DLL only if you want to change the DLL, without having to change the entire program.

3) Because DLLs are language independent, so when people of different language habits develop a large-scale project, the use of DLLs to facilitate the communication of the program system, of course, Delphi developed DLLs can also be used in systems such as visual basic,c++.

The following is a few examples of Delphi development of dynamic Connection library methods and specifications.

Section I. building and invoking methods of dynamic connection libraries

First, dynamic Connection library construction

1. Create a basic module of a dynamic connection library

File---New---other---DLL Wizard

Library Project1;

{If the DLL outputs a procedure or function with a long character type parameter, or if the function return type is a long string or a constructed type with a long string element, Object Pascal specifies that the SHAREMEM unit must be added to the uses portion of the program, whether it be a DLL or a procedure calling it. The SHAREMEM unit is an interface unit introduced from the DelphiMM.DLL DLL, so this program must be distributed with DelphiMM.DLL. Delphi recommends that you use the Pchar or shortstring type parameter when passing string information in order to avoid using DELPHIMM.DLL. (Original English)}

Uses

Sysutils, Classes;

( Code section)

{$R *.res}

Begin

End.

Change the project name to Math (Save projectas ...) and write the necessary functions

Library Math;

Uses

Sysutils,

Classes;

function Mround (d:double):D ouble; stdcall; rounding Function: Mathematical rounding function does not begin// Same as Delphi Banker Rounding Method

Result:=int (d*100+0.5)/100;

End

Exports

Mround;

{$R *. RES}

Begin

End.

From this example, you can see several rules of the DLL program:

1) in a DLL program, the output function must be declared as StdCallto replace the optimized register with the standard Win32 parameter passing technique. The calling convention for the parameter. The calling convention is as follows:

Instruction Pass Order parameter Delete

StdCall from left to right functions

Cdecl invoking aspects from right to left

Pascal from left to right function aspect

Register from left to right function aspect

Description

Register, by default, is the only way to pass the parameters of the CPU register, and it is the fastest way to pass it; Pascal: the invocation protocol is for backward compatibility only, that is, the old version is compatible;
Cdecl: Many routines written in the C and C + + languages, as well as routines that require the parameters to be purged by the caller, stdcall: And Safecall are primarily used to invoke Windows API functions, where Safecall is also used for dual interfaces.

2) all output functions must be listed under the exports clause, which allows the subroutine to be seen outside the DLL.

Exports

mround[name ' aliases '];

Lists the interface names that the user uses for this function. Although aliases are not required, it is best to give individual names so that the user program can find this function more easily, and also to point out that Delphi 6.0 cancels the index that is allowed in Delphi 5.0 . If you also specify the interface name with index, Delphi 6.0 will prompt the error.

The MessageBox prompt method is given in the example, which mainly wants to illustrate a problem:

The MessageBox (0, ', ', MB_OK) is a Windows-provided API function that makes the program smaller.

ShowMessage ("), is a function provided by VCL, due to the multiple compilation of VCL, the program will be relatively large.

This means that when you write a DLL program, you should try to avoid compiling the VCL multiple times. As an example, the two methods are listed here.

2. Save

3. Compilation: PROJRCT---Build Math.DLLL

This completes the writing of a simple dynamic connection library.

Second, calls to dynamic connection libraries

1. Static calls

First (if it is required to be declared under implementation in the form, this example runs directly in the program file DPR without the form) to invoke the Declaration function Mround (d:double): Double; stdcall; external '  Math.dll ';

The complete calling program is as follows:

program test;

Uses

Windows

Messages,

Sysutils,

Forms,

Dialogs,

Stdctrls;

var

d:double;

info:double;

{$R *.res}

Begin

Application.initialize; /program initialization and start running

D: = Strtofloat (InputBox (' Input window ', ' Please enter the number to be rounded, ' 0 '));

MessageBox (0, Pchar (floattostr (mround (d))), ' Results ', MB_OK ormb_iconinformatio

{Call DLL Function}

Application.Run;

End.

2. Dynamic Invocation ( instance)

                            type   & nbsp;                                                                         Tshowform = function (Ahandle:thandle; acaption:string): BOOL; stdcall;               {creates a function class here}                                                                             Edllloaderror = Class (Exception);//Create an Error record class at the same time
                                                                                                  tmaincltr = Class (Tform)//Does not change here, the system is automatically generated (call DLL form of the application's form Class)                                                                                       

Private

{Private declarations}

Public

{Public declarations}

End

Var

maincltr1:tmaincltr;

Implementation

{$R *. DFM}
Functions, Procedure definitions
Procedure tmaincltr. Toolbutton1click (Sender:tobject); Invoke event for button: Call procedure
var Libhandle:thandle;
Showform:tshowform;
Begin
Application.title:= ' DLL file test program ';
{Attempt to mount DLL file}
Libhandle: = LoadLibrary (' Mgrform. DLL ');
Try
If Libhandle = 0 Then
Raise Edllloaderror.create (' Unable to load DLL (unable to successfully load MGRFORM.DLL) ');
@ShowForm: = GetProcAddress (Libhandle, ' showform ');
If not (@ShowForm = nil) Then
ShowForm (Application.handle, ' personnel Information management ')//Call out Form
Else
Raiselastwin32error;
Finally
FreeLibrary (Libhandle); Unload the DLL.
End
End
============== END ==================

second section DLL in the Delphi form

First, the steps to implement form reuse using DLLs are:

1. In the Integrated development environment (IDE), design a form according to your own needs;

2. Write a function or procedure for the output. in this function or procedure, the design of the form is instantiated ;

The method is:

1) First make the form according to the normal method, but in the interface area, the interface function is declared as follows

function CreateForm (capt:string): String;stdcall;

2) Add the interface function under implementation

function CreateForm (capt:string): String;stdcall;

var Form1:tform1;

Begin

form1:=tform1.create (application); The design of the form is instantiated

{ pass a application parameter and use it to create a form.} }

Form1.show;

FORM1.CAPTION:=CAPT;

End

3. Repeat steps 1 and 2 until you have completed the design of all reuse forms;

4. Open File---New---Other---dll to build the DLL file. Add reserved word exprots. Exports is the output function name or procedure name. (Generate form)

5. Compile and generate the DLLs file, to declare:

Uses

Unit1 in ' Unit1.pas ';

Exports { write interface identifier}

createform name ' Myform ';

6. Invoke the Reuse form in other applications.

A call to reuse a form is exactly the same as a call to a general DLLs function or procedure

DLL creation and invocation of files in Delphi

I. Notation of the Function procedure:

Library Forstdll;

Uses
Sysutils,
Classes;

{$R *. RES}
1. Define function specific process and output interface mode
// --------------------------------
Function 1
Function: Data 3 times magnification function
// --------------------------------
function Penniestosoins (Sourceresult:integer): Integer;stdcall;
Begin
If Sourceresult>0 Then
RESULT:=SOURCERESULT*3//results stored in result
Else
Result:=sourceresult;
End

Exports
Penniestosoins; 2. Function Export definition

End.

Two. Creating a form in a DLL
=======================
1. Create a DLL project and add a set form

Library Mgrform;
Uses
Sysutils,
Classes,
Mgrperfm in ' Mgrperfm.pas ' {formperson};//1.form code (as in normal form)

{$R *. RES}
Exports
SHOWFORM;//2. Definition of function output export
Begin
End.

2. Settings of the form set in the DLL
===========================================
Unit MGRPERFM;

Interface

Uses
Windows, Messages, Sysutils, Classes, Graphics, Controls, Forms, Dialogs,
Comctrls, Toolwin, imglist;

Type
Tformperson = Class (Tform)
Private
{Private declarations}
Public
{Public declarations}
End

This variable is no longer used, change it to a place, and put it in implementation. as follows (one of the changes)
Var
Formperson:tformperson; {Declares the form function exit}//to change the second

function showform(ahandle:thandle; acaption:string): BOOL; stdcall;

{Form instantiation Function}

Implementation

{$R *. DFM}
Functions, Procedure definitions
function showform(ahandle:thandle; acaption:string): BOOL;
Var
Formperson:tformperson; Define the form class (above is placed here)
Begin
Copy application handle to DLL ' s Tapplication object
Copy the application handle to the DLL's due program object
Application.handle: = Ahandle;
Formperson: = tformperson.create (application);//Create Control Tform
Try
Formperson.caption: = acaption;
formperson.showmodal;//Show This form
Pass the date back in Result
Result: = False; Return success Value
Finally
Formperson.free;
End
End

Three. Calls to functions and forms in DLLs
==========================
1. Calling method One: static reference

Implementation//The DLL that called the function is indicated below this

{$R *. DFM}
referencing DLL internal functions
function Penniestosoins (Sourceresult:integer): Integer;
Stdcall;external ' Forstdll. DLL ';

........

2. Call method Two: Dynamic reference
==============
Type//Create a function class here
// -------------------------------
{Forst, define a procedural data type, this should reflect the
Procedure that's exported from the DLL. }
{Create A new exception class to reflect a failed DLL load}


Tshowform = function (ahandle:thandle; acaption:string): BOOL; stdcall;

Edllloaderror = Class (Exception);//Create an Error record class at the same time
//  -------------------------------
Tmaincltr = Class (Tform)//Here is the same, the system is automatically generated

......

Procedure tmaincltr. Toolbutton1click (Sender:tobject);
Call event for var//button: Call procedure
Libhandle:thandle;
Showform:tshowform;
Begin
Application.title:= ' DLL file test program ';
{Attempt to mount DLL file}
Libhandle: = LoadLibrary (' Mgrform. DLL ');
Try
If Libhandle = 0 Then
Raise Edllloaderror.create (' Unable to load DLL (unable to successfully load MGRFORM.DLL) ');
@ShowForm: = GetProcAddress (Libhandle, ' showform ');
If not (@ShowForm = nil) Then
ShowForm (Application.handle, ' personnel Information management ')//Call out Form
Else
Raiselastwin32error;
Finally
FreeLibrary (Libhandle); Unload the DLL.
End
End
============== END ==================

Delphi Foundation III Writing and invoking DLL files

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.