Creating a DLL


To create a new DLL in Delphi, select File ® New ® Other, then select the Delphi Projects node in the Item Categories tree, and finally double-click the DLL Wizard item at the right.

image from book
Figure 21-1: Selecting the DLL Wizard

The DLL Wizard creates the main source file for the DLL that looks almost exactly like the source code generated for a standard application. The only difference is that the file begins with the reserved word library instead of program (see Listing 21-1).

Listing 21-1: The basic source code for a DLL

image from book
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 as parameters or function results. 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. To avoid using BORLNDMM.DLL, pass string information   using PChar or ShortString parameters. } uses   SysUtils,   Classes; {$R *.res} begin end.
image from book

All that you have to do now is add a routine above the begin-end block and you're done. When you do that, you'll have an internal routine that you'll be able to use in the DLL but not from outside applications. If you want to call the routine from other applications and DLLs, you'll have to export it. To export a routine by name, add it to the exports list. The exports list has the same syntax as the uses list, except that in the exports list each item is a routine, not a unit.

The exports list is usually written immediately above the main begin-end block. Take a look at Listing 21-2 to see the source code of the simple image from book FirstLib.dll that exports a single function.

Listing 21-2: A simple DLL

image from book
library FirstLib; function Max3(Num1, Num2, Num3: Integer): Integer; stdcall; begin   Result := Num1;   if Num2 > Result then Result := Num2;   if Num3 > Result then Result := Num3; end; { export the Max3 function } exports   Max3; begin end.
image from book

When you add a routine to the exports list, you are exporting the routine by name. You can also export the routine under a different name using the name directive or you can export the routine by ordinal value using the index directive. However, the use of the index directive is discouraged.

Here's how you can export a routine by ordinal value or under a different name:

exports   Max3 name 'MyMax3Function',   SaySomething index 1;



Inside Delphi 2006
Inside Delphi 2006 (Wordware Delphi Developers Library)
ISBN: 1598220039
EAN: 2147483647
Year: 2004
Pages: 212
Authors: Ivan Hladni

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net