tags:

views:

178

answers:

4

I have a Python module, wrapper.py, that wraps a C DLL. The DLL lies in the same folder as the module. Therefore, I use the following code to load it:

myDll = ctypes.CDLL("MyCDLL.dll")

This works if I execute wrapper.py from its own folder. If, however, I run it from elsewhere, it fails. That's because ctypes computes the path relative to the current working directory.

My question is, is there a way by which I can specify the DLL's path relative to the wrapper instead of the current working directory? That will enable me to ship the two together and allow the user to run/import the wrapper from anywhere.

+3  A: 

You can use os.path.dirname(__file__) to get the directory where the Python source file is located.

Matthew Flaschen
Thank you very much. That's exactly what I was looking for.
Frederick
+1  A: 

I always add the directory where my DLL is to the path. That works:

os.environ['PATH'] = os.path.dirname(__file__) + ';' + os.environ['PATH']
windll.LoadLibrary('mydll.dll')

Note that if you use py2exe, this doesn't work (because __file__ isn't set). In that case, you need to rely on the sys.executable attribute (full instructions at http://www.py2exe.org/index.cgi/WhereAmI)

Chris B.
+1  A: 

Expanding on Matthew's answer:

import os.path
dll_name = "MyCDLL.dll"
dllabspath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + dll_name
myDll = ctypes.CDLL(dllabspath)

This will only work from a script, not the console nor from py2exe.

fmark
I like the use of os.path.sep in general, but are there any Windows installations that don't use ';' for a path separator?
Chris B.
This path separator is a directory separator, i.e. '\' on Windows. This takes a different approach to yours, loading the dll through its absolute file path rather than modifying the PATH environmental variable. I think I like yours more, as it has a fallback to loading the default system dll if one is not supplied.
fmark
A: 

How do I run any .dll file in Python? Any working examples and instructions? regards. David [email protected]

david
Davide, this space where you mistakenly posted your question is meant only for answers to the question on the top of this page. You'll be better served if you ask this as a new question by clicking on 'Ask Question' link on the top right corner.
Frederick