4

I am trying to load a dll form python code with ctypes and it raised an error.

my python code:

import ctypes
from ctypes import *
hllDll = ctypes.WinDLL ("c:\\Users\\saar\\Desktop\\pythonTest\\check.dll")

and this raised error:

Traceback (most recent call last): 
  File "C:\AI\PythonProject\check.py", line 5, in <module> 
    hllDll = ctypes.WinDLL("c:\\Users\\saar\\Desktop\\pythonTest\\check.dll") 
  File "C:\Python27\lib\ctypes\__init__.py", line 365, in __init__ 
    self._handle = _dlopen(self._name, mode) 
WindowsError: [Error 126] The specified module could not be found 

I google it and every post i saw guide to write the dll path with two backslash, or import ctypes and then write : from ctypes import *.

Saar Arbel
  • 91
  • 1
  • 7
  • 1
    This thread maybe useful for you: http://stackoverflow.com/questions/7586504/python-accessing-dll-using-ctypes – West Jan 05 '16 at 08:40

1 Answers1

2

The check.dll might have dependencies in the folder so prior to using it, use could first call os.chdir to set the working directory, for example:

import ctypes
import os

os.chdir(r'c:\Users\saar\Desktop\pythonTest')
check = ctypes.WinDLL(r'c:\Users\saar\Desktop\pythonTest\check.dll')

You can avoid needing two backslashes by prefixing your path string with r.

Alternatively, LoadLibraryEx can be used via win32api to get the handle and pass it to WinDLL as follows:

import ctypes
import win32api
import win32con

dll_name = r'c:\Users\saar\Desktop\pythonTest\check.dll'
dll_handle = win32api.LoadLibraryEx(dll_name, 0, win32con.LOAD_WITH_ALTERED_SEARCH_PATH)
check = ctypes.WinDLL(dll_name, handle=dll_handle)

Microsoft had developed a DLL dependency checker called depends.exe but unfortunately stopped further development of this a long time ago. There are though now other similar utilities which do the same. The idea is that if you are trying to load your DLL, but it requires a another DLL to work which you don't have, the DLL load will fail without giving an obvious reason. By using these tools you can locate where the problem is.

Microsoft recommend using Dependencies which is available on github.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97