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...
#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
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.
If it is helpful...
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With