ctypes:Multiple library access problem

Stefan Schukat SSchukat at dspace.de
Thu May 6 05:56:59 EDT 2010


Massi wrote:
> > Hi everyone,
> >
> > in my script I need to execute multiple separated loading of the same
> > dll library, in order to handle the internal variables with different
> > threads.
> > Consider the followin piece of code:
> >
> > lib1 = cdll.LoadLibrary("MyLib.dll"))
> > lib2 = cdll.LoadLibrary("MyLib.dll"))
> >
> > lib1.var1 = 0
> > lib2.var1 = 1
> >
> > Now, if I print the value of lib1.var1 I get 1, that is lib1 and lib2
> > point to the same memory space. Is there a way to create "different
> > instances" of the same library? Or, alternatively, does it exist any
> > workaround to avoid lib1 and lib2 share the same memory space?
> >
> > Thanks in advance.
> >
> >   
> Windows will not load the same DLL twice into the same process in two 
> different places.  When it detects that it's the same one, it simply 
> returns the same handle as the earlier one, without any loading or 
> initializing.
> 
> With some DLL's, you might get away with copying it to a different 
> filename, and then loading each as an independent item.  But unless you 
> wrote it yourself, or it has been documented for that behavior, you're 
> taking a big risk.
> 
> On the other hand, if the DLL was written with threading in mind, then 
> it'll get notified for each new thread you create, and it can manage TLS 
> (thread local storage) rather than using extern vars.  I have no idea 
> how to get at those from Python, however.
> 
> DaveA
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
  
The statement from Dave is as far true as the library is loaded without a path. Hence windows
searches the system path and always finds the same file. If you load a DLL with an absolute path
window will place the dll multiple times into the process.
e.g.

lib1 = cdll.LoadLibrary(r"c:\temp\MyLib.dll")
lib2 = cdll.LoadLibrary(r"d:\temp\MyLib.dll")

This has the same effect as renaming the library on the disk.

   Stefan




More information about the Python-list mailing list