Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exposing C++ class in Python ( only ET_DYN and ET_EXEC can be loaded)

Tags:

python

boost

I was looking at here to see how to expose c++ to Python. I have built Python deep learning code which uses boost-python to connect c++ and python and it is running ok, so my system has things for boost-python alread setup. Here is my hello.cpp code (where I used WorldC and WorldP to clearly show the C++ and Python class name usage in the declaration. I don't know why the original web page is using the same class name World to cause confusion to beginners.)

#include <boost/python.hpp>
using namespace boost::python;

struct WorldC
{
    void set(std::string msg) { this->msg = msg; }
    std::string greet() { return msg; }
    std::string msg;
};

BOOST_PYTHON_MODULE(hello)
{
    class_<WorldC>("WorldP")
        .def("greet", &WorldC::greet)
        .def("set", &WorldC::set)
    ;
}

and this is how I made hello.so

g++ -shared -c -o hello.so -fPIC hello.cpp -lboostpython -lpython2.7 -I/usr/local/include/python2.7

When I run import hello in python, it gives me this error.

>>> import hello
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: ./hello.so: only ET_DYN and ET_EXEC can be loaded

Can anybody tell me what's wrong?
(I'm using anaconda2 under my home directory for python environment, but since my deep learning code builds ok with boost-python, there should be no problem including boost/python.hpp in my system directory)

like image 251
Chan Kim Avatar asked Jul 08 '16 06:07

Chan Kim


1 Answers

I've long forgotten about this problem and got to revisit this issue today.
I found two problems. The first problem was that I gave -c option which made the compiler only compile the source and not link. The second problem was that the library name was wrong(I search /usr/lib64 and there was libboost_python.so, so it should be -lboost_python instead of -lboostpython). So the correct way to build it is :

g++ -shared -o hello.so -fPIC hello.cpp -lboost_python -lpython2.7 -I/usr/local/include/python2.7

I found it runs ok in python. :)

like image 190
Chan Kim Avatar answered Oct 07 '22 23:10

Chan Kim