3

I am trying to call some of my C++ machine learning code in Python. I have tried multiple other methods, such as this question and this explanation, both of which are very similar. I followed these to the letter, with the same filenames and code.

For example, I have the following C++ code...

file.cpp

#include <iostream>

void some_code()
{
    std::cout << "Hello world!";
}

extern "C"
{
    void hello_there() { some_code(); }
}

I then compile it with...

g++ -c -fPIC file.cpp -o foo.o

g++ -shared -Wl,-soname,lib.so -o lib.so foo.o

code.py

from ctypes import cdll

lib = cdll.LoadLibrary('./lib.so')

lib.hello_there()
Traceback (most recent call last):
  File "c:\some-path-here\1 - calling-cpp-with-python.py", line 5, in <module>
    lib = cdll.LoadLibrary('./lib.so')
  File "C:\Users\USERNAME\AppData\Local\Programs\Python\Python310\lib\ctypes\__init__.py", line 452, in LoadLibrary
    return self._dlltype(name)
  File "C:\Users\USERNAME\AppData\Local\Programs\Python\Python310\lib\ctypes\__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
FileNotFoundError: Could not find module 'C:\some-path-here\lib.so' (or one of its dependencies). Try using the full path with constructor syntax.

What am I doing wrong? I have also tried with compiling it to a DLL file, and adding __declspec(dllexport) before the "void" in the extern bit.

Additional Notes

If it is helpful...

  • I am on Windows 10
  • I am using the MinGW G++
  • The name of the directory with the files in has spaces in it.
  • This is running on Python 3.10, but the error also occurs in 3.9
Password-Classified
  • 769
  • 1
  • 9
  • 24

2 Answers2

1

Looks like a path issue based on the error. I was able to quickly try out your example, and it worked for me. This error probably has nothing to do with iostream, but you could confirm that by changing the function quickly to use printf.

I do not have experience working on c++ in windows 10, but could you check if you're able to find the library file in python, before accessing using something like the below code

import os    
print(os.path.exists('./lib.so'))
anirudh
  • 3,920
  • 2
  • 18
  • 35
1

I encountered exactly the same problem on Win 10, MinGW & Python 3.7-3.10.

I finally used dependencywalker and found out that the importing relies on the compiler environment. With exaction of dependent dlls I solved this problem. Using static compile mode also helps.

eyllanesc
  • 221,139
  • 17
  • 121
  • 189
Serena
  • 19
  • 3
  • Thanks for making the modifications; if you happen to remember, can you include the command line option (or other brief instruction) on how to enable static linking on the MinGW environment? – nanofarad Mar 23 '22 at 01:48