G S
G S

Reputation: 36818

Python ctypes: loading DLL from from a relative path

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.

Upvotes: 31

Views: 53232

Answers (5)

Vinod KC
Vinod KC

Reputation: 39

If you are using an __init__.py file, the folder in which that python file contains is well known for the compiler. You can use that folder name for a relative path. For example, if I have a folder named foo and it contains an __init__.py file, then this foo folder can be used as a base folder. Assume that I have a helper.dll inside foo, I can open the dll like this.

helper = ctypes.WinDLL(r"foo\helper.dll")

This will work.

Upvotes: 0

Shtefan
Shtefan

Reputation: 808

Another version:

dll_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'MyCDLL.dll')
myDll = ctypes.CDLL(dll_file)

Upvotes: 0

fmark
fmark

Reputation: 58547

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.

Upvotes: 14

Chris B.
Chris B.

Reputation: 90191

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)

Upvotes: 12

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

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

Upvotes: 29

Related Questions