I have made a DLL which exports several functions (with stdcall).
I want to have some of them accept parameters or not. So a lazy programmer can just call it without any parameters.
I read somewhere on a forum that default parameters don't work in DLL-s. Is my only option is creating 2 functions with different names, like:
procedure DoSomething();
begin
DoSomethingParams(1, 'Hi');
end;
procedure DoSomethingParams(one: Integer; two: PChar);
begin
//
end;
? Or maybe there is a more elegant way to achieve this?
Default parameters can be used with DLLs. But the default parameters must be declared when the function is imported rather than when it is exported. That's because default parameters are implemented at the call site. The caller detects that parameters are missing and generates code to supply the missing parameters.
So you can use default parameters when you import the DLL, provided that the language that consumes the DLL supports that.
In the DLL code, export the function. You can specify default parameters there if you wish, but it won't have any effect for the consumer of the DLL.
In the code that imports the DLL function, declare your default parameters. It is the default values declared at this point that matter.
Since DLLs are typically used to provide language neutral interfaces, and since some languages do not support default parameters, it is rare to use them in DLL interfaces.
Related
I'm currently struggling with the following:
I need to create two different DLL's, which do exactly the same but are looking to a different DB. The two DB's are nothing alike.
My dll's should be handling the communication with those different DB's.
So that the main program chooses which dll he wants to use.
I want to be sure each dll has exactly the same procudes/functions/...
I was thinking of using interfaces.
But I can't figure out how to create global interfaces. the dll's belong to the same projectgroup.
I do believe you're making a "mountain out of a molehill" thinking you need 2 different DLLs. But if you choose the last of my suggested options, you should find it fairly easy to switch between a 2 DLL solution and 1 DLL solution.
Option 1
This is the most straightforward:
Create a new unit.
Add your DLL interface (the exports).
Include the unit in both projects.
unit DllExportIntf;
interface
uses
DllExportImpl;
exports DoX;
implementation
end.
Note that this unit uses DllExportImpl which will also have to be included in both projects. However, you'll need 2 different files with the same name in 2 different locations in your file system. So each DLL project will have different implementations.
Now whenever you make a change to your interface, your projects won't compile until you've updated each of the DllExportImpl units.
What I don't particularly like about this solution is the need for units with the same name but different behaviour. Since you intend having both DLLs in the same project group: I should warn you that I've experienced the IDE getting confused by duplicate unit names.
Option 2
Place the exports into a shared include file.
library DllSharedExportsImpl1;
uses
DllExportImpl1 in 'DllExportImpl1.pas';
{$I ..\Common\DllExports.inc}
The DllExports.inc file will only include your exports clauses. E.g.
exports DoX;
This has the advantage that now each DLL can use different unit names for the different implementations. And if you change your include file, neither project will compile until you've updated its implementation unit to accommodate the change.
Note that this does come with its own set of problems. The way includes work: the compiler effectively shoves the contents of the include file into the unit at compile time. So what looks like line 7 to the IDE is entirely different to the compiler. Also editing include files can be a bit of a nuisance because context can only be determined where the file is included making editor support quite impractical.
Option 3
This option is a little more work, but provides much better long-term maintainability.
You do this by implementing your interface via polymorphic objects. In this way, both DllProjects will also share the routines that are actually exported. When each DLL initialises, it sets the concrete implementation to be used.
Your DLL interface could look something like this.
unit DllExportIntf;
interface
type
TAbstractImpl = class(TObject)
public
procedure DoX; virtual; abstract;
end;
procedure AssignDllImpl(const ADllImpl: TAbstractImpl);
procedure DoX;
exports DoX;
implementation
var
GDllImpl: TAbstractImpl;
procedure AssignDllImpl(const ADllImpl: TAbstractImpl);
begin
if Assigned(GDllImpl) then
begin
GDllImpl.Free;
end;
GDllImpl := ADllImpl;
end;
procedure DoX;
begin
GDllImpl.DoX;
end;
end.
When you initialise your DLL, you can call:
AssignDllImpl(TDllImpl_1.Create);
A clear advantage of this approach is that if there is any common code between your 2 DLLs, it can be included in your base implementation. Also, if you can change an existing method DLL in such a way that it does not require a change to TAbstractImpl, you possibly will only need to recompile your DLLs.
Furthermore, if you need to change existing virtual abstract methods, you will have to update the overrides in your concrete implementations accordingly.
WARNING If you add a new virtual abstract method, your projects will still compile with warnings that you are creating objects with abstract methods. However, you should always treat warnings as errors. If you do, this caveat won't be a problem.
NOTE: As mentioned earlier, using this approach you should be able to fairly easily switch between single DLL and 2 DLL solutions. The difference basically boils down to which units are included in the project, and how you initialise the global.
It may also be worthwhile mentioning that you could even eliminate the global altogether by implementing a Handle to use with each of your DLL routines. (Similar to Windows.) Bear in mind that there are technical issues when trying to pass objects between DLL and application code. This is why instead of passing objects, you use a "handles" to objects and encapsulate the actual object instances internally.
Considering all that was said, I believe that you would be more successful if you design your solution with packages, not DLLs. A package is a DLL, but rich in symbols, so Delphi can be a better use of it. Particularly, the symbols declared inside the package will more easily be loaded by your application, with a much higher level of abstraction. It´s what the Delphi IDE uses to load components.
So, following this design, this is what you have to do:
Declare your interfaces in units existing in a package named (for instance) DBServices.dpk. Here is an example of such an unit:
unit DBService1;
interface
uses
....;
type
IService1 = interface
[....] // here goes the GUID
procedure ServiceMethod1;
procedure ServiceMethod2;
// and so on...
end;
implementation
end.
So, above you created an unit that declares an interface. Your aplication can use that interface anywhere, just reference the package in your application and use it in other units and you will have the access to the symbols declared.
Declare the implementation class for that very same interface in another unit of another package, for instance, dedicated to SQLServer (SQLServerServices.dpk):
unit SQLServerService1;
interface
uses
DBService1, ....;
type
TSQLServerService1 = class(TInterfacedObject, IService1)
protected // IService1
procedure ServiceMethod1;
procedure ServiceMethod2;
// and so on...
end;
implementation
procedure TSQLServerService.ServiceMethod1;
begin
// Specific code for SQL Server
end;
procedure TSQLServerService.ServiceMethod2;
begin
// Specific code for SQL Server
end;
...
end.
Above you declared an implementing class for the interface IService1. Now you have two packages, one declaring the interfaces and other implementing those interfaces. Both will be consumed by your application. If you have more implementations for the same interfaces, add other packages dedicated to them.
One important thing is: you have to have a factory system. A factory system is a procedure ou class that will create and return the implementations for your application from each package.
So, in terms of code, in each service package (the ones that implement the interfaces) add a unit named, for instance, xxxServiceFactories, like this:
unit SQLServerServiceFactories;
interface
uses
DBService1;
function NewService1: IService1;
implementation
uses
SQLServerService1;
function NewService1: IService1;
Result := TSQLServerService1.Create;
end;
end.
The code above declares a function that creates the SQL Server implementation and returns it as an interface. Now, if you call a method from the interface returned, you will be actually calling the specific implementation of it for SQL Server.
After loading the package, you will have to link to that function in the very same way you would do if working if a DLL. After you have the pointer for the function, you can call it and you will have the interface in your application's code:
...
var
service1: IService1;
begin
service1 := NewService1;
service1.ServiceMethod1; // here, calling your method!
end;
The model I described in this answer is the one I used in a similar scenario I had to deal with in the past. I presented general ideas that work, but you have to understand the fundamentals of packages and interfaces to really master the technique.
A comprehensive explanation on those matters would be very long for an answer here, but I guess it will be a good starting point for you!
What you want to do is create a COM component project. Define your methods on that & implementations for one DB. Then create a second COM component that uses the same interface.
On the off-chance that your question is more about the fundamentals of Delphi, I've added another answer which may be more helpful to you than the first one. My first answer focused on getting 2 DLLs to expose the same methods (as per the main body of your question). This one focuses on the last 2 sentences of your question:
But I can't figure out how to create global interfaces. The dll's belong to the same project group.
Based on this, it sounds like you're looking for an option to "mark an interface as global so that projects in the same group can use them". Delphi doesn't need a special feature to do this because it's trivially available if you understand certain fundamental principles.
When you create a new unit, it is by default added to the current project. However if you want to share the unit between multiple projects, it's a good idea to save it to a different folder so it's easy to see that it's shared. Your first DLLs project file should look something like this.
library Dll1;
uses
DllSharedIntf in '..\Common\DllSharedIntf.pas';
You can define your "global" interface in the DllSharedIntf unit. E.g.
unit DllSharedIntf;
interface
type
IDllIntf = interface
['{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}']
procedure DoX;
end;
implementation
end.
NOTE: Because the interface type is declared in the interface section of the unit, it is considered "global" because other units are able to use it. But this doesn't automatically make it available to other projects.
You now have to add the shared unit to your other project so it becomes available for use by other units in that project. To do this:
Activate Dll2
Select Project and Add to Project...
Find DllSharedIntf and add it.
Delphi will automatically update your project source file to include the unit.
library Dll2;
uses
DllSharedIntf in '..\Common\DllSharedIntf.pas';
Now in each DLL project you can add a separate implementation unit. E.g. For Dll1:
unit DllImpl1;
interface
uses
//It's very important to indicate that this unit uses the shared unit.
//Otherwise you won't be able to access the "global types" declared
//in the interface-section of that unit.
DllSharedIntf;
type
TDllImpl1 = class(TInterfacedObject,
//Any types defined in the interface-section of any units that
//this unit **uses**, can be accessed as if they were declared
//in this unit.
IDllIntf)
protected
//The fact that this class is marked as implementing the IDllIntf
//means that the compiler will insist on you implementing all
//methods defined in that interface-type.
procedure DoX;
end;
implementation
NOTE This answer only covers sharing an interface between projects. You'll still need to expose the functionality of the DLLs via appropriate exports. You'll need an approach similar to option 3 of my other answer.
Summary
We don't usually talk about "global interfaces" in Delphi. It's generally understood that anything declared in the interface section of a unit is globally accessible. (We do make more of an issue about global variables due to their dangers though; but that's an entirely different topic.)
In Delphi:
Whenever you want one unit (A) to make use of functionality defined in another unit (B), you need to add unit B to the uses clause of unit A.
Whenever you want a project to use a unit created in another project, you need to add the unit to the project. (TIP: It's a good idea to put such units in a separate folder.)
NOTE: When sharing units between projects, the project group is actually irrelevant. Projects don't need to be in the same group to share units. All you need to do is ensure the project can access the unit so that other units in your project can uses it.
I'm trying to figure out a safe way of passing objects from a main app to a DLL (for a plugin system).
The idea is to use the main app's TZConnection (database access from Zeos Lib) in the dll's.
I'd rather not use Runtime Packages, and DLL must be the way to go (I don't need BPL's need to recompile each time, and have no idea of how to use COM).
I've been told it's possible to do it with Interfaces.
I've never used them before, but been messing around with it, and managed to do it... But, I don't know if I did it right (as in, safe).
Here's my Interface unit.
unit PluginIntf;
interface
uses
ZConnection, ZDataSet;
type
IQueryResult = interface ['{743AB77E-7897-403E-A0D9-4D02748E565D}']
function GetRecordCount: Integer;
function GetDataSet: TZQuery;
end;
IPluginHost = interface ['{A5A416B4-437E-4A1E-B228-0F94D54840B0}']
function RunSql(const SQLString:WideString): IQueryResult;
end;
IPlugin = interface ['{8D9591C3-5949-4F0A-883E-6ABD02597846}']
function GetCaption: WideString;
end;
implementation
end.
In IQueryResult, I'm passing a TZQuery. It works, but... Is it safe?
Is there any other way to wrap it in the Interface?
Thank you
Nuno Picado
TZQuery is a class. Therefore it is not safe to pass one across the module boundary unless you use runtime packages. Use a class with DLLs and you actually have two separate types, one in each module.
You are correct that interfaces are safe for this but you need to restrict yourself to DLL interop safe types. That is simple types, records, pointers to arrays, interfaces, or combinations of these types.
You need to wrap TZQuery with an interface that exposes it's functionality.
After much searching, it looks like I have to assign RegisterComponentsProc and RegisterPropertyEditorProc, which I have done.
However, I thought that I could call my design time Register function, i.e. <myComponentUnit>.Register();.
When I do I get stack overflow, because, well ...
procedure myComponentUnit.Regiter;
begin
RegisterPropertyEditor(TypeInfo(Integer),
TMyComponent, 'myProperty', TMyProperty);
end;
procedure RegisterPropertyEditor(PropertyType: PTypeInfo;
ComponentClass: TClass; const PropertyName: string;
EditorClass: TPropertyEditorClass);
begin
if Assigned(RegisterPropertyEditorProc) then
RegisterPropertyEditorProc(PropertyType, ComponentClass, PropertyName,
EditorClass);
end;
So, I call .Register();
which calls RegisterPropertyEditor()
which call RegisterPropertyEditorProc()
which calls RegisterPropertyEditor() <=== aaargh!!
So, what should I have in the body of my RegisterPropertyEditorProc ?
After further searching, it looks like I want to call DesignEditors.RegisterPropertyEditor() directly, but it is not in the interface section ...
There is no point in trying to register a property editor at run-time, as it is not usable at run-time to begin with. It is only usable within the IDE during design-time.
Delphi does not include the source for the DesignEditors unit; its implementation is provided solely in the DesignIDE package. That package has access to IDE internals, such as the list of registered property editors. The IDE assigns values to the RegisterComponentsProc and RegisterPropertyEditorProc callback functions. As you noticed, RegisterPropertyEditor calls RegisterPropertyEditorProc. The IDE provides its own function to handle that event.
If you want to register a property editor at run time, then your program plays the role of the IDE. You need to provide implementations for those callback functions to register the property-editor classes with your own property-editing framework. You could probably just keep everything in a simple list. Then, when you want to know what kind of editor to display for a certain type of property, consult the list to find the best match.
You're correct that you should call your units' Register procedures. But that's how you initiate the registration process, not how you implement it. That part's up to you; Delphi doesn't provide any of this for you.
In one of the Delphi demo applications, I've stumbled upon some syntax that I didn't know the Delphi compiler accepted:
// ......\Demos\DelphiWin32\VCLWin32\ActiveX\OleAuto\SrvComp\Word\
// Main.pas, line 109
Docs.Add(NewTemplate := True); // note the assignment
I can't seem to reproduce this type of parameter passing in my own code, and I never see anyone use it. So these are my questions:
Can i use this in "normal" methods and is it part of "the Delphi Language", or is this some compiler hack for automation objects?
What's needed in order to be able to use this?
Is this anything like C#4's named and optional parameters?
Additional information: I usually pass
records or simple classes when there
are many optional parameters to
methods, but it looks like I wouldn't
need that with this syntax. I'm aware
of default parameter values, but their
usefulness is limited because you
cannot provide any parameters to the
right of an omitted one. In JavaScript
I'm using this named parameter style
all the time (be it with different
syntax), and it's powerful.
Clearly the Delphi language supports named parameters since they appear right there in sample Delphi code. Delphi supports named parameters on automation objects, which are objects that implement the IDispatch interface. There are restrictions on the types the parameters and return types can have; in particular, they can't be Delphi classes.
I don't think the convenience you seek from named parameters would outweigh the performance hit you'd take by having every method call routed through the IDispatch.Invoke method. A call may also need to use GetIDsOfNames first. You don't see this in more code because late binding is usually something people try to avoid. Use early binding whenever possible to avoid the cost of looking up dispatch IDs and indirect method invocations.
Delphi supports optional parameters in non-automation code by allowing default values. You can omit the actual parameters for any parameter with a default value as long as you also omit the actual parameters of all subsequent parameters — the compiler ensures that a function's declaration allows for that.
I think optional parameters are overrated. They save time for the (one) person writing the code, but not for the (many) people reading the code. Whoever's reading it needs to know what the default values will be of any unspecified parameters, so you may as well just provide all the values explicitly anyway.
If you declare your procedure like so:
procedure DoSomething(AParam : integer = 0);
... it will assume a value of 0 for the parameter if it isn't given. As I recall, parameters with default values have to be at the end of the call, so like this:
procedure DoSomething(AFirstParam : string; AParam : integer = 0);
not like this:
procedure DoSomething(AParam : integer = 0; ASecondParam : string);
It is basically "some compiler hack for automation objects". I sometimes have to use it for Excel and Word automation.
e.g.
MSExcel.Application.Cells.Replace(What:='', Replacement:='', LookAt:=xlPart,
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=True, ReplaceFormat:=True);
Is equivalent to VBA
Application.Cells.Replace(What='', Replacement='', LookAt=xlPart, _
SearchOrder=xlByRows, MatchCase=False, SearchFormat=True, ReplaceFormat=True)
One of the problems I often run into, is that I will include 'Windows' in my uses clause, and then I will later add 'JwaWinBase' for some specific calls.
However, many of the functions in the 'Windows' unit are the same as in JwaWinBase, and I start getting errors in my main unit, all over the place, until I fix all my calls by pre-pending the correct unit name, like this:
Old:
CreateProcessAsUser(...)
New:
Windows.CreateProcessAsUser(...)
JwaWinBase.CreateProcessAsUser(...)
What I want to know, is if there is a way to have the unit name automatically pre-pended to every call to a function in another unit? This way, before I added JwaWinBase to my uses clause, I could have the 'Windows' unit name pre-pended to any function calls. Then adding JwaWinBase wouldn't give me any errors.
I'm currently using Delphi 2007.
There isn't.
However, the function calls are handled in the reverse order they're in the uses clause, so that if you have this:
uses
Windows, JwaWinBase;
... it will call Jwa functions by default. However, if you reverse them:
uses
JwaWinBase, Windows;
... it should call the Windows functions by default, and you can preface your Jwa functions as required.
If you really need the resolution on a per-routine base, you could try inline forwarders:
procedure Blah; inline;
begin
Windows.Blah;
end;
procedure Blubb; inline;
begin
JwaWinBase.Blubb;
end;
// later:
procedure UseThem;
begin
Blah; // calls Windows.Blah
Blubb; // calls JwaWinBase.Blubb
end;
at the beginning of the implementation section (completely untested :-)).
Maybe it's enough to just switch the order of the two units in the uses clause.
If you use an editor like CodeRush (D7 and before) or Castalia or even the template feature of D2009, you can create templates that expand to what you want AS you enter them. Then you can keep the Windows, jwaWinBase order in the uses section. You can set jcpau to expand to jwaWinBase.CreateProcessAsUser while cpau expands to CreateProcessAsUser or to Windows.CreateProcessAsUser depending on your preference. You'd only have to go through the various functions in jwaWinBase and make templates for them to be safe.
Otherwise, I think it's search and replace on a case-by-case basis.