Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading and accessing multiple ctype instances

Tags:

python

ctypes

I have some existing C code that I am working with in Python. I am able to load the library using the following commands:

library_path = '/full/path/to/my/library.dylib'
lib1 = cdll.LoadLibrary(library_path)

The problem is that I need to have multiple instances of this library, for example:

lib2 = cdll.LoadLibrary(library_path)

This creates a second instance, but both seem to have the same memory location (handles are the same). I've tried copying and renaming library.dylib to library1.dylib and library2.dylib, but this doesn't change how they load. The problem is that when I call function in lib1, global and state variables in lib2 are modified. For example:

lib1.open('/path/to/myfile')  # open a file for processing
lib1.run()   # This will do something with the file

lib2.open('/path/to/anotherfile')  # open a file for processing
lib2.run()   # This will do something with the file

lib1.close() # Closes library 1

lib2.run()   # This fails because lib1.close() also closes lib2

Is there any way to load these library instances in way that they remain 'contained'? The C code that I am trying to load is very large legacy software...do I need to do some rewriting?

Here is a link that I found addressing a similar problem, but doesn't help me that much: http://www.gossamer-threads.com/lists/python/python/826703

Any help is greatly appreciated.

like image 658
Castrona Avatar asked Jan 27 '15 22:01

Castrona


1 Answers

As you noticed, some OS refuses to load several instances of the same DDL in the same process. If everything else failed, you might use the multiprocessing module to fork your program, and load each DLL in a different process. – Sylvain Leroux Jan 27 '15 at 22:20

like image 154
Nickolay Avatar answered Nov 06 '22 22:11

Nickolay