Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can call C++ code in Python, that uses <iostream>

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
like image 506
Sam Avatar asked May 17 '26 11:05

Sam


1 Answers

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'))
like image 61
anirudh Avatar answered May 20 '26 01:05

anirudh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!