Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when loading .dll from a different directory using python ctypes.CDLL()

Tags:

python

ctypes

I have to following directory structure:

MainProject  
    |    ...project files  
    |    rtlsdr\  
    |    |    rtlsdr.dll
    |    |    ...other .dll's etc.  

I am using the function CDLL() in the library ctypes to load rtlsdr.dll. It works fine when my working directory is rtlsdr\:

$ cd rtlsdr
$ python
> from ctypes import *
> d = CDLL('rtlsdr.dll')

However, when I try to load the file from another directory:

$ cd MainProject
$ python
> from ctypes import *
> d = CDLL('rtlsdr\\rtlsdr.dll')

I get an error:

WindowsError: [Error 126] The specified module could not be found.

What is the problem here?

like image 626
hazrmard Avatar asked Feb 03 '26 16:02

hazrmard


1 Answers

A DLL may have other DLL dependencies that are not in the working directory or the system path. Therefore the system has no way of finding those dependencies if not specified explicitly. The best way I found is to add the location of the directory containing dependencies to the system path:

import os
from ctypes import *
abs_path_to_rtlsdr = 'C:\\something\\...\\rtlsdr'
os.environ['PATH'] = abs_path_to_rtlsdr + os.pathsep + os.environ['PATH']
d = CDLL('rtlsdr.dll')

Once the current session is closed, the PATH variable will return to its original state.

Another option is to change working directory, but that might affect other module imports:

import os
os.chdir(abs_path_to_rtlsdr)
# load dll etc...
like image 86
hazrmard Avatar answered Feb 05 '26 05:02

hazrmard