smilingbuddha
smilingbuddha

Reputation: 14660

Calling C++ from python using boost python: introductory example not working

I am interested in using Boost.Python to call C++ functions from my Python scripts.

This example here is an introductory example on Boost python's home-pagewhich I am unable to run. Can someone help me out with this?

This is what I tried

I created a file named hello_ext.cpp as follows

#include <boost/python.hpp>
char const* greet()
{
   return "hello, world";
}


BOOST_PYTHON_MODULE(hello_ext)
{
    using namespace boost::python;
    def("greet", greet);
}

I then compiled it to a shared library as follows

g++ -c -Wall -Werror -fpic hello_ext.cpp -I/usr/include/python2.7
g++ -shared -o libhello_ext.so hello_ext.o

Finally firing up the ipython interpreter I tried to import hello_ext but got the following error message. Where did I go wrong?

In [1]: import hello_ext
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-18c4d6548768> in <module>()
----> 1 import hello_ext

ImportError: ./hello_ext.so: undefined symbol: _ZNK5boost6python7objects21py_function_impl_base9max_arityEv

Upvotes: 1

Views: 337

Answers (1)

J.J. Hakala
J.J. Hakala

Reputation: 6214

You should include some libraries in your link command,

 g++ -shared -Wl,--no-undefined hello_ext.o -lboost_python -lpython2.7 -o hello_ext.so

With -Wl,--no-undefined linker option it will be an error if some symbols are missing.

Upvotes: 3

Related Questions