I normally use Python but I now want to learn a bit about interfacing c++ with Python. For this I wrote a simple program in c++:
#include <iostream>
using namespace std;
int SomeCalculation(float x){
int decision = 0;
if (x > 1){
decision = 1;
}
return decision;
}
int main()
{
float a = 0.5;
cout << "\n" << SomeCalculation(a) << "\n\n";
return 0;
}
Using CodeBlocks I compiled it and it runs fine. I now want to import and use SomeCalculation() into Python. As far as I understand (from this) I need to compile the cpp program into a shared library to be imported in Python. I found this extensive SO thread about that, but I'm totally lost in it.
I've got a main.cpp file (the code above) which I need to compile into an .so file (right?). I tried the following: g++ -fPIC -g -ggdb -c main.cpp -o main.so
. I then try to import the resulting .so file into my python program as follows:
import ctypes
print ctypes.CDLL('main.so').SomeCalculation(2)
But I get the following error:
Traceback (most recent call last):
File "/home/kram/c++/cmod/importcpp.py", line 2, in <module>
print ctypes.CDLL('main.so').SomeCalculation(2)
File "/usr/lib/python2.7/ctypes/__init__.py", line 365, in __init__
self._handle = _dlopen(self._name, mode)
OSError: main.so: cannot open shared object file: No such file or directory
Since I've never really (manually) compiled a c++ program I'm kind of lost in the command to do so. Does anybody have a tip on how to compile this as a shared library? All tips are welcome!