cannot load dll in python with ctypes

孤人 提交于 2021-02-07 18:31:06

问题


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 *.


回答1:


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)


来源:https://stackoverflow.com/questions/34607082/cannot-load-dll-in-python-with-ctypes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!