How to import python module from .so file?

balki picture balki · Jun 10, 2012 · Viewed 74.6k times · Source
[me@hostname python]$ cat hello_world.cc
#include <string>
#include <Python.h>
#include <boost/python.hpp>

namespace {
  std::string greet() { return "Helloworld"; }
}

using namespace boost::python;

BOOST_PYTHON_MODULE(hello_world)
{
  def("greet",greet);
}

[me@hostnmae python]$ g++ -c -fPIC hello_world.cc -I/path/to/boost/headers -I/path/to/python/headers -o hello_world.o
[me@hostname python]$ g++ -shared -Wl,-soname,libhello_world.so -o libhello_world.so  hello_world.o
[me@hostname python]$ python
Python 2.7.1 (r271:86832, Jan 10 2011, 09:46:57)
[GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.append('.')
>>> import hello_world
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named hello_world
>>>

I created the .so file as shown above but I'm not able to import inside python. what am I missing?

Answer

Cat Plus Plus picture Cat Plus Plus · Jun 10, 2012

It must be called hello_world.so, not libhello_world.so.