Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I put the .so file from Boost.Python so I can import it as a module, and how do I use it with both Python 2 and 3

I have the following file in a folder called cpp_examples.

#include <boost/python.hpp>
#include <string>

const std::string hello() {
return std::string("hello, zoo");
}

BOOST_PYTHON_MODULE(zoo) {
// An established convention for using boost.python.
using namespace boost::python;
def("hello", hello);
}

And I ran the following command to compile.

sumith@rztl516-Lenovo-G575:~/cpp_examples$ g++ zoo.cpp -I/usr/include/python2.7 -I/usr/lib/x86_64-linux-gnu/ -lboost_python  -lpython2.7 -o zoo.so -shared -fPIC

It got compiled and gave me a zoo.so file. And when I tried to import and run the zoo.hello() within the same folder it worked but it is not importing outside the cpp_examples folder

sumith@rztl516-Lenovo-G575:~/cpp_examples$ python2
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import zoo
>>> zoo.hello()
'hello, zoo'
>>> exit()

The following is outside cpp_examples folder.

sumith@rztl516-Lenovo-G575:~$ python2
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import zoo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named zoo
>>> 

What might be the reason for not getting imported of that folder ?. And while compiling I checked for python3 it is not compiling at all where I changed -lpython2.7 to -lpython3.4 and -I/usr/include/python2.7 to I/usr/include/python3.4 in above command but it is giving me error while compiling

/usr/bin/ld: cannot find -lpython3.4

If I can get answers for these two questions it would be of a great help. Thank you.

like image 446
Sumith Avatar asked Oct 29 '22 10:10

Sumith


1 Answers

As @Omnifarious originally stated in a comment, you should look at the directories present in sys.path to find places where you can put your .so file. That's where Python will look by default when the import statement is found.

When you run Python in the directory containing the .so, it finds it easily since the first entry is sys.path is actually the current directory.

As for linking, you should generally provide the the flags that pythonX.Y-config --ldflags gives you, as described in the section Compiling and Linking under Unix-like systems.

The example in the documentation also provides sample output for it using Python 3.4:

$ /opt/bin/python3.4-config --ldflags
-L/opt/lib/python3.4/config-3.4m -lpthread -ldl -lutil -lm -lpython3.4m -Xlinker -export-dynamic
like image 183
Dimitris Fasarakis Hilliard Avatar answered Nov 04 '22 06:11

Dimitris Fasarakis Hilliard