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