python cdll can't find module

12,726

Solution 1

I had the same issue with trying to load magic1.dll - this file depends on two other .dll's, and when I moved magic1.dll from my current working dir - I could not load.

This workaround helped:

pathToWin32Environment = os.getcwd() + "/environment-win32/libmagic/"
pathToDll = pathToWin32Environment + "magic1.dll"
if not os.path.exists(pathToDll):
    #Give up if none of the above succeeded:
    raise Exception('Could not locate ' + pathToDll)
curr_dir_before = os.getcwd()
os.chdir(pathToWin32Environment)
libmagic = ctypes.CDLL('magic1.dll')
os.chdir(curr_dir_before)

Solution 2

The exact error message would help know for sure, but ctypes.dll(path) doesn't seem valid to me.

eg. I get this, with Python 2.7:

>>> ctypes.dll("kernel32.dll")
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'module' object has no attribute 'dll'

Perhaps you meant this instead:

>>> _lib = ctypes.CDLL(os.path.join(path, 'my.dll'))
Share:
12,726
jdsmith2816
Author by

jdsmith2816

This user's bio was too excellent to display.

Updated on June 28, 2022

Comments

  • jdsmith2816
    jdsmith2816 almost 2 years

    I have a library consisting of two dll files and one python wrapper.

    I currently have code based on these three files being in the same parent directory as my main python file. I am now attempting to refactor things before I continue development and would like to move said library code into it's own lib/ directory. Unfortunately, nothing I've tried helps.

    import ctypes
    
    _lib = ctypes.cdll["./my.dll"]
    

    The above code located in the python wrapper file loads the dll perfectly fine in it's original location. I've tried various ways of loading it in the new location such as:

    from ctypes import *
    import os
    
    path = os.path.dirname(os.path.realpath(__file__))
    _lib = ctypes.CDLL(os.path.join(path, 'my.dll'))
    

    However python always throws an exception saying unable to find the module.. I have copy and pasted the path to verify that it is in fact the valid absolute path to the .dll file

    Does anyone know what I need to do in order to relocate this library to a sub folder? I could always leave it where it is but I simply hate clutter.

  • jdsmith2816
    jdsmith2816 over 13 years
    Yes, sorry; I was typing the second codeblock from memory since I had already reverted things back to how they were so that I could continue with other refactorings; question edited to reflect the proper call. If it would help I'll get the exact error message when I get home later tonight but it was simply reporting that it could not find the module.