RE: DLLs for Beginners

"Andre du Plessis" <[email protected]>
Newsgroups gmane.comp.lang.delphi.programming
Message-ID <000c01c3452e$1d5137e0$1c0044c0@ANDRE>
Richard, 

First of all congratulations your DLL document seems to be quite popular
however, 
I would like to add to your DLL document, I noticed that you did not add
some of the stuff I mentioned before, which though I think is important,
you also mentioned threads might be a problem. I think this is an
important topic because whether you use threads in your DLL or not
multithreaded apps might want to use your dll, so I would like to add a
very basic simple techniques, Delphi has a IsMultiThread variable,
whenever beginthread is called IsMultiThread is set to true, this tells
the memory manager to wrap itself around a critical section making the
memory manager thread safe, without it, it is not thread safe!.

So every DLL that might be used in a multithreaded app, must set this
variable to true! Because the BeginThread is called from the main
process and not the DLL, the dll does not know to set it's IsMultiThread
variable.

Secondly when using global variables they must use the threadvar
directive, this is done on compiler level but I assume utilizes critical
sections as well. Secondly the best way to deal with this is to use
Thread local storage, the windows API includes:

TLSAlloc
TLSFree
TLSGetValue and
TLSSetValue

The api stores these in the thread's local storage and is truly
thread-safe.
You should initialize these values in your dll's Entry procedure

Below I wrote a simple example of a thread-safe dll
The function MyObject returns the instance of the global variable that
uses Thread local storage. 

It is also important to note that TLSGetValue Must be called on the
initialization for the main thread and then on Thread Attach for every
new thread. 

Interface

  Type 
    TMyObject = class(TObject);

Implementation

threadvar
  FObjectIndex : DWORD = 0;

Function MyObject : TMyObject;
Begin
  Result := TMyObject(TLSGetValue(FObjectInstance))
End;

Procedure InitMyObject;
Begin
  TLSSetValue(FObjectInstance, Pointer(TMyObject.Create));
End;

Procedure FreeMyObject;
Begin
  TMyObject(TLSGetValue(FObjectInstance)).Free;
End;

procedure DllEntry(Reason: Integer);
begin
  case Reason of
    DLL_THREAD_ATTACH:
      Begin
         InitMyObject;
              end;
    DLL_THREAD_DETACH:
      Begin
        FreeMyObject;
              end;
  end;
end;


initialization
  IsMultiThread := True;
  FObjectIndex := TLSAlloc;
  DLLProc := @DllEntry;
  InitMyObject;

Finalization
  FreeMyObject;
  TlsFree(FObjectInstance);


Lastly we can look at the topic of the RTTI and DLL's another day.



-----Original Message-----
From: Richard Le Mesurier (Investec Employee Benefits)
[mailto:[email protected]] 
Sent: Friday, July 04, 2003 3:59 PM
To: Brent Boswell (E-mail); Mike Currin (E-mail); Ivor Chalton (E-mail)
Cc: '[email protected]'; '[email protected]';
'[email protected]'; '[email protected]'
Subject: DLLs for Beginners

Hi, guys,

Well, here is what I have put together. As I said, its very very
informal,
and really its just my attempt at solidifying my own thoughts on the
topic
before I go away for close on a month's leave - without this doc I am
sure
returning to work would be a lot harder (to the SA guys... hehe I'm off
to
30 degree weather in France! :)

So in the spirit of sharing that's gotten me so far in my own learning,
here's what I have learnt.

There are two projects in the attachment. The one is the DLL and the
other
is a program that calls the DLL.

The actual DLL itself is useless - it does pretty much nothing (it
reverses
a string...). The code was not as important to me as cracking how to
write a
DLL - I was scared of this strange concept and now I have found out that
there is nothing too hard about it. A few extra rules to follow... I'm
sure
a real working DLL will have its complex parts, and also surely some
extra
tricks to remember, but that's the same with any REAL vs LEARNING
programs
(anyone tried to learn to write a REAL program after copying a "Hello
world"
program?)

Andre mentioned that it would be handy to know why and when to write a
DLL,
and I guess also why and when to link statically or dynamically. I don't
really know, haven't given it much thought, sorry. My aim was to learn
HOW,
so that when I got a valid reason at work to use one, I could.

Please, if anyone has anything to add, please do. Make this a living
document and maybe between us all we can help a new generation of guys
along. If its handy, pass it along; its not really my work, all I did
was
rewrite other people's work and arrange it my own way. But most
importantly,
if I have made errors (in code, concept or just judgement) please
correct
them to me. I can read about them when I get back.

One last favour to the guys on the mailing list... I am on leave from
Monday, so if anyone else from the list is interested in this stuff, can
one
of you please send it along. I won't be around to read their requests.

Cheers
Richard

 <<DoPWord.zip>> 
(this is a Winzip file)

NOTICE - This message contains privileged and confidential 
information intended only for the use of the addressee 
named above. Any review, retransmission, dissemination, 
copying, disclosure or other use of, or taking of any 
action in reliance upon, this information by person or 
entities other than the intended recipient is prohibited. 
If you have received this message in error, please notify 
the sender by return email and delete this message. 
This message should not be copied or used for any purpose 
other than intended, nor should it be disclosed to any 
other person. Any views expressed in this message are those 
of the individual sender, except where the sender specifically
 states them to be the view of Investec Group, its 
subsidiaries or associates. The Investec Group is not 
liable for the security of information sent by e-mail at 
your request, nor for the proper and complete transmission 
of the information contained in the communication nor for 
any delay in its receipt. Please note that the recipient 
must scan this e-mail and any attached files for viruses 
and the like. The Investec Group accepts no liability of 
whatever nature for any loss, liability, damage or expense 
resulting directly or indirectly from the access of any files 
which are attached to this message.


------------------------ Yahoo! Groups Sponsor ---------------------~-->
Save up to 80% on top-quality inkjet cartridges and get your order fast!
FREE shipping on orders $50 or more to the US & Canada. Shop at Myinks.com!
http://www.c1tracking.com/l.asp?cid=5511
http://us.click.yahoo.com/v2G7ND/KfUGAA/ySSFAA/i7folB/TM
---------------------------------------------------------------------~->

Delphi Tips & Tutorials...
http://www.delphicollection.com
---------------------------------------------------------------
Unsubscribe:[email protected]
List owner:[email protected]
--------------------------------------------------------------- 

Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.