boost python hello程序导入错误

20

包含

using namespace boost::python;

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

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

编译和构建成功

~/boost$ g++ -fPIC -I/usr/include/python2.6 -c hello.cpp 
~/boost$ g++ -shared hello.o -o hello.so

但是当从Python侧导入时,会出现错误。

>>> import hello.so
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: ./hello.so: undefined symbol: _ZNK5boost6python7objects21py_function_impl_base9max_arityEv
>>> 
4个回答

14

通过 "No such file or directory" error with Boost Python 解决了这个问题。

g++ -c -fPIC hello.cpp -o hello.o
g++ -shared -Wl,-soname,hello.so -o hello.so  hello.o -lpython2.6 -lboost_python

对我有帮助。我希望这尽可能清晰,因为我已经苦恼了半个小时 ;)


7

与此处的其他帖子相同

g++ -c -fPIC hello.cpp -o hello.o
g++ -shared -Wl,-soname,hello.so -o hello.so  hello.o -lpython2.6 -lboost_python

但是我想强调"-lpython2.6 -lboost_python"位置的重要性。如果你把它们放在输入文件(hello.o)前面,它们会被忽略(不会链接到最终的hello.so)。至少对于g++(Ubuntu/Linaro 4.6.3-1ubuntu5)来说是这样的。

简单来说,http://ubuntuforums.org/showthread.php?t=496287建议:

  g++ <.cpp or .o file(s)> [LDFLAGS] [LIBS] -o [appname]

4
据我理解,链接顺序敏感的原因是GNU ld 编译时链接器是单遍链接器:它从命令行从左到右选取要解决的符号,并维护一个未解决符号的列表。因此,如果将hello.o放在末尾,会引入新的未解决符号(这些符号在libpython2.6.solibboost_python.so中被定义),但现在无法解决这些符号,因为没有任何向右定义这些符号的内容。 - Emmet

4

7
解决方案是将 "-lpython2.6 -lboost_python" 添加到链接行中?我不完全清楚你从另一个线程中学到了什么... - Christopher Bruns
@ChristopherBruns,你最终解决了这个问题吗? - Tijme

3

我曾经遇到过同样的问题,后来发现我的类缺少了一个构造函数。


刚刚遇到了同样的错误,这个错误太难以察觉了!非常感谢您的评论,否则我可能要花好几天才能发现这个问题。 - John C

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接