2016-07-08 72 views
2

我在看here以查看如何向Python公开C++。我已经构建了Python深度学习代码,它使用boost-python连接C++和python,并且它运行正常,所以我的系统有一些boost-python alread setup。 这里是我的hello.cpp代码(我使用WorldC和WorldP来清楚地显示声明中的C++和Python类名称用法,我不知道为什么原始网页使用相同的类名称World导致混淆初学者。)在Python中暴露C++类(只能加载ET_DYN和ET_EXEC)

#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) 
    ; 
} 

,这是我如何使hello.so

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

当我运行的进口你好Python中,它给了我这个错误。

>>> 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 

有人可以告诉我什么是错?
(我用我的anaconda2主目录为Python环境下,但因为我的深度学习代码生成OK与升压蟒蛇,应该是包括在我的系统目录boost/python.hpp没问题)

回答

4

我很久以前就已经忘记了这个问题,今天又重新讨论了这个问题。
我发现了两个问题。第一个问题是我给了-c选项,它使编译器只编译源代码而不是链接。第二个问题是库的名称是错误的(我搜索/ usr/lib64和libboost_python.so,所以它应该是-lboost_python而不是-lboostpython)。所以建立它的正确方法是:

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

我发现它在python中运行正常。 :)