Delphi & DLLs II
Creating
DLL's using Delphi:
- creating a DLL within Delphi is very similar to creating a normal
application, except:
- when starting a new project, from the menu, select File:New then
select DLL
- this creates a project file as usual except:
- instead of it being headed "program", it is headed
"library"
- the application.run line is not included
- a form is not automatically created for you to use
- add a new unit to your project via File:New and select Unit
- write the function code as usual in the implementation section and
the corresponding function name and parameters in the interface
section but suffixing it with "export; stdcall;"
- eg.
- interface
- function MyFunction(S:String):String; export;
stdcall;
- implementation
- function MyFunction(S:String):String;
- begin
- result := UpperCase(S);
- end;
- nb. the suffix "export" was only needed in
Delphi 1 to deal with Win 3.x and its segmented memory, so it is
no longer needed
- nb. the suffix "stdcall" should be used in
Delphi 2 and higher to ensure Delphi compiles the DLL so any
other Window's application can access it, not just Delphi. It
tells Delphi to use Window API's stdcall convention of pushing
all arguments onto the stack in a standard order rather than
Delphi's method of loading them into registers which results in
faster code execution but only Delphi programs can access the
DLL.
- the new unit will be added to the project unit automatically
- ie. in its uses clause the line will be added:
- UnitName in 'Unitname.pas';
- now you just need to itemise the exported functions in your project
file:
- open the project file (eg. from menu, Project:View Source)
- after the uses clause and before the begin end section, create a
section as follows:
- exports
- MyFunction1;
- MyFunction2;
- etc;
- now its ready to compile, just choose from menu, Project:Compile;
- NB. if you try to run it, it will compile it but not run it as
DLL's cannot be ran alone
- see how easy it is to create a DLL in Delphi!!
Getting
the path of a DLL:
- if you call ExtractFilePath(ParamStr(0)) from a DLL you will get the path
of the web server, so if you want the path of the DLL itself use:
- function ScriptPath: String;
- var path: array[0..MaxPathLength-1] of char;
- begin
- if IsLibrary then
- SetString(Result, path, GetModuleFileName(HInstance, path,
SizeOf(path)))
- else Result := ParamStr(0);
- end;
-
Some notes relating to creating DLLs using
Delphi:
- Delphi 4 gives a warning that if Pascal strings are passed within any
exported routines either as strings or within records, then you must place
"ShareMem" as the 1st item in the project's uses clause and you
must deploy Borland's share memory DLL with your DLL ie. BorlNDMM.dll
- to avoid this, pass PChars or ShortStrings instead of Pascal strings
as PChars are the native string type in Windows