Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ctypes: loading DLL from from a relative path

Tags:

python

ctypes

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.

like image 241
Frederick The Fool Avatar asked Jun 05 '10 13:06

Frederick The Fool


2 Answers

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

like image 54
Matthew Flaschen Avatar answered Oct 07 '22 19:10

Matthew Flaschen


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.

like image 23
fmark Avatar answered Oct 07 '22 18:10

fmark