I'm on windows, using anaconda with python 3 and setuptools.
I'm having problems with loading a DLL inside my package. I tried following the advice in 'Packaging resources with setuptools/distribute' as well as 'Python copy a DLL to site-packages on Windows' but I seem to be missing something.
So, my package looks like:
setup.py
package
|--- __init__.py
|--- main.py
|--- subpackage
|--__init__.py
|--foo.py
|--bar.DLL
Inside foo.py
I do:
import ctypes
my_dll = ctypes.cdll.LoadLibrary('bar.dll')
This works, when I run my script in the console. However, as soon as I make everything into a package and install it (e.g. via setuptools and pip), I seem to be unable to load the dll.
Inside setup.py
I set package_data={'':['*.dll', '*.h', '*.lib']}
. After installtion, I can see all the files being correctly placed in the install location. Once I try to import my package, I get the error:
File "path\to\subpackage\foo.py", line 3, in <module>
my_dll = ctypes.cdll.LoadLibrary('bar.dll')
[...]
OSError: [WinError 126] Das angegebene Modul wurde nicht gefunden
(Could not find the given module)
So, I'm pretty sure, I need to change the loading of my dll
file in the first place at runtime but I don't know how.
I'm looking for a solution, that still allows me to run the single file foo.py
in editor, but allows me to use the same file inside a package after installation.
Update Edited for clarity.
Update 16.12.2019 I found one more thing:
I tried the below answer from Sergey which is
import os
this_dir = os.path.abspath(os.path.dirname(__file__))
my_dll = ctypes.cdll.LoadLibrary(os.path.join(this_dir, 'bar.dll'))
This works only, if my current workdir is equal to ...\package\subpackage
, so I assume that LoadLibrary
does not even try to search the given path and only takes the filename instead.