【问题标题】:exposing C++ class in Python ( only ET_DYN and ET_EXEC can be loaded)在 Python 中公开 C++ 类(只能加载 ET_DYN 和 ET_EXEC)
【发布时间】:2016-07-08 06:38:56
【问题描述】:

我正在查看 here 以了解如何将 c++ 暴露给 Python。我已经构建了 Python 深度学习代码,它使用 boost-python 来连接 c++ 和 python,并且运行正常,所以我的系统有用于 boost-python 的设置。 这是我的hello.cpp代码(这里我使用了WorldC和WorldP在声明中清楚地展示了C++和Python类名的用法。不知道为什么原来的网页使用了相同的类名World造成混淆初学者。)

#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 时,它给了我这个错误。

>>> 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环境,但是由于我的深度学习代码使用boost-python构建得很好,所以在我的系统目录中包含boost/python.hpp应该没有问题)

【问题讨论】:

    标签: python boost


    【解决方案1】:

    我早就忘记了这个问题,今天要重新审视这个问题。
    我发现了两个问题。第一个问题是我给了 -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 中运行良好。 :)

    【讨论】:

      猜你喜欢
      • 2018-10-22
      • 1970-01-01
      • 2019-03-05
      • 2020-10-08
      • 1970-01-01
      • 2021-02-21
      • 2014-05-12
      • 1970-01-01
      • 2011-03-18
      相关资源
      最近更新 更多