How to compile, create shared library, and import c++ boost module in Python

二次信任 提交于 2019-12-06 06:59:53

As requested a tiny working example:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#include <boost/python.hpp>
#include <boost/python/raw_function.hpp>
#pragma GCC diagnostic pop


namespace python = boost::python;

class ORM
{
public:
  void foo(){std::cout << "foo" << std::endl;}
};

BOOST_PYTHON_MODULE(orm)
{
python::class_<ORM>("ORM")
    .def("foo", &ORM::foo)
;
}

Build command line:

g++ -I /usr/include/python2.7 -fpic -c -o orm.o orm.cpp
g++ -o orm.so -shared orm.o -lboost_python -lpython2.7

Running the python module:

$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import orm
>>> o = orm.ORM()
>>> o.foo()
foo
>>> 

If an attempt to import module is returning an undefined symbol error then very likely in runtime there is different version of library being used than the one was used to build the python module. You can use ldd to print shared library dependencies to have a look if everything is ok, for example: ldd orm.so and check if paths to libraries are the same like the ones used for building the module.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!