Search code examples
pythondllctypes

Import dll using ctypes in virtual environment


As per title I am using ctypes to access a .dll file from python. Everything works fine if I run the following code from my normal shell:

import ctypes as ct
import os
path = '\\some_path\\file.dll'
print(os.path.isfile(path))
lib = ct.CDLL(path)

Output:

True

However if I try to run it from a virtual environment the same code gives me the output + error:

True
Traceback (most recent call last):
File ".\Test-c.py", line 4, in <module>
    lib = ct.CDLL(path)
  File "C:\Users\au684834\Miniconda3\envs\development\lib\ctypes\__init__.py", line 351, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found

Reading around I couldn't find this specific problem, does anyone know a simple solution? Note that the file is found so the path is likely not the problem. I have to run this inside a virtual environment because this is an addition to a larger project.

Many thanks

EDIT: modified the path to avoid confusion with the Windows backslash problem. I have also added os.path.isfile() to show that the file exists and it is found.


Solution

  • So, it turns out the problem was not ctypes, permissions or anything like that: the problem was the virtual environment. in fact there was a problem, not only with my environment, but with the miniconda installation itself. I was not able to reinstall the environment nor to update miniconda. I solved everything by reinstalling miniconda from scratch and recreating the environment. Now the code above works as expected.