且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

boost_python导入错误:模块未定义初始化函数

更新时间:2023-10-22 22:33:40

BOOST_PYTHON_MODULE中使用的名称必须与您生成并导入到 python .so库的名称匹配.>

First off: I looked at the related questions, but they are not very helpful unfortunately. I'm trying to wrap an enum and a class from an external library.

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

#include <libvpsc/rectangle.h>
using vpsc::Rectangle;
using vpsc::Dim;

BOOST_PYTHON_MODULE(adaptagrams)
{
    enum_<Dim>("dim")
        .value("x", vpsc::XDIM)
        .value("y", vpsc::YDIM)
        .value("unset", vpsc::UNSET)
    ;

    class_<Rectangle>("Rectangle",
        init<double, double, double, double, optional<bool> >())

        .add_property("centerX", &Rectangle::getCentreX)
        .add_property("centerY", &Rectangle::getCentreY)
        .add_property("width", &Rectangle::width, &Rectangle::set_width)
        .add_property("height", &Rectangle::height, &Rectangle::set_height)
    ;
}

and compile with:

g++ -fPIC -I/usr/include/python2.7 -c adaptagrams.cpp -o adaptagrams.o
g++ -shared -Wl,-soname,adaptagrams.so -o adaptagrams.so adaptagrams.o -lpython2.7  -lboost_python -lvpsc

However, when I try to import the .so module, I get an error:

ImportError: dynamic module does not define init function (PyInit_adaptagrams)

Any ideas?

Update: When I restart Python and try the import, the first error I get is:

ImportError: ./adaptagrams.so: undefined symbol: _ZN8topology13computeStressERKSt6vectorIPNS_4EdgeESaIS2_EE

When I try it again, the 2nd one is the dynamic import from above (2.7) and a segfault (3.2). Boost is compiled against both 2.7 and 3.2 and I am linking the right ones on each approach.

Update 2: The tutorial code from the boost_python page works:

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

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

BOOST_PYTHON_MODULE(constructor)
{
    class_<Hello>("Hello", init<std::string>())
        .def("greet", &Hello::greet)
        .def("set", &Hello::set)
    ;
}

Same compilation:

g++ -fPIC -I/usr/include/python2.7 -c constructor.cpp -o constructor.o
g++ -shared -Wl,-soname,constructor.so -o constructor.so constructor.o -lpython2.7 -lboost_python

The name used in BOOST_PYTHON_MODULE must match the name of the .so library you generate and import into python.