Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass and return objects to and from a DLL?

Tags:

dll

delphi

I need to return objects from a DLL made in Delphi, to an app made in Delphi, too. The objective is to do a subsystem that can be modify in the future without to modify the main app. So, I imagine developing the subsystem in a DLL is a (good??) idea... i am programming in Windows XP, Delphi 7. I did read DLLs only return basic data type, but there must to be a way to do that...

Best regards.

like image 992
DelphiProgrammer Avatar asked Nov 04 '09 20:11

DelphiProgrammer


Video Answer


3 Answers

I prefer to apply COM to such a model, which allows you to create external "objects" which you then can direct from within your application. Creating COM objects in Delphi is extremely simple, use your ActiveX creation methods to create an ActiveX library and then create COM objects. You then use the interface unit in your main application, and when you CoCreate an instance of the object it loads the appropriate DLL. The only tricky part of this is that your com objects must be registered on the system to function properly... which in the Win7/Vista world requires elevated access... although once this is done, it is seamless.

like image 120
skamradt Avatar answered Oct 01 '22 17:10

skamradt


The BEST way is to use a COM wrapper as suggested by skamradt.

It is possible, but not a good idea to pass object references as pointers to DLL's. Refer particularly to Peter Haas's comments.

If you do pass an object from a Delphi DLL to a Delphi app you will have the following problems:

You must use the same version of Delphi for the app and DLL.

Both app and DLL MUST have the same implementation of the object - or at least identical layout of all fields in the class - OK if you are using standard objects such as TStringList.

You should use shared memory or runtime packages, otherwise you will get weird access violations.

I have had to maintain code where this was done - it was nightmarish as you couldn't change classes without a lot of re-compiling.

like image 41
Gerry Coll Avatar answered Oct 01 '22 19:10

Gerry Coll


You can use interfaces and most of your problems, wrt compiler/rtl versions or even other languages just go away. Delphi's interfaces are always IUnknown-compatible, which makes them compatible with most OO-enabled languages on Windows.

One thing to keep in mind, though: Don't use AnyString, stick to WideString, which is the Stringtype used by COM.

like image 21
Robert Giesecke Avatar answered Oct 01 '22 17:10

Robert Giesecke