0

I am trying to run a C function in Python. I followed examples online, and compiled the C source file into a .so shared library, and tried to pass it into the ctypes CDLL() initializer function.

import ctypes
cFile = ctypes.CDLL("libchess.so")

At this point python crashes with the message:

Could not find module 'C:\Users\user\PycharmProjects\project\libchess.so' (or one of its dependencies). Try using the full path with constructor syntax.

libchess.so is in the same directory as this Python file, so I don't see why there would be an issue finding it.

I read some stuff about how shared libraries might be hidden from later versions of python, but the suggested solutions I tried did not work. Most solutions were also referring to fixes involving linux system environment variables, but I'm on Windows.

Things I've tried that have not worked:

  • changing "libchess.so" to "./libchess.so" or the full path
  • using cdll.LoadLibrary() instead of CDLL() (apparently both do the same thing)
  • adding the parent directory to system PATH variable
  • putting os.add_dll_directory(os.getcwd()) in the code before trying to load the file

Any more suggestions are appreciated.

maniha
  • 1
  • 1
  • Check [\[SO\]: Python Ctypes - loading dll throws OSError: \[WinError 193\] %1 is not a valid Win32 application (@CristiFati's answer)](https://stackoverflow.com/a/57297745/4788546) the ***Conclusions*** section at the end. Most likely your *.dll* (*.so*) has dependencies that can't be loaded, because they are not found. Please add more details on how you build your *.dll*. [\[SO\]: How to create a Minimal, Reproducible Example (reprex (mcve))](https://stackoverflow.com/help/minimal-reproducible-example). – CristiFati Dec 02 '22 at 22:46

1 Answers1

0

Solved:

Detailed explanation here: https://stackoverflow.com/a/64472088/16044321

The issue is specific to how Python performs a DLL/SO search on Windows. While the ctypes docs do not specify this, the CDLL() function requires the optional argument winmode=0 to work correctly on Windows when loading a .dll or .so. This issue is also specific to Python versions greater than 3.8.

Thus, simply changing the 2nd line to cFile = ctypes.CDLL("libchess.so", winmode=0) works as expected.

maniha
  • 1
  • 1