4

I've managed to compile a Boost.Python 'first try' but am unsure how to import it into python and call the methods it contains. My source file is as follows:

#include <stdlib.h>
#include <string>
#include <boost/python.hpp>

using namespace boost::python;

int test(int i)
{
       fprintf(stderr, "%s:\n", __FUNCTION__);
       return i * 5;
}

BOOST_PYTHON_MODULE(ipg)
{
       using namespace boost::python;
       def("test", test);
}

My makefile contains:

# Which compiler?
CC=c++

# Which flags for object files?
OFLAGS=-c -Wall -fPIC

# Which flags for the output binary?
BFLAGS=-Wall -shared -o ipg

# Which flags for boost python?
BPFLAGS=-I/usr/include/python2.7
BLIBS=-lpython2.7 -lboost_python -lboost_system

# Make.
all: source/python.cpp
    $(CC) $(BOUT) $(BFLAGS) $(BPFLAGS) $? $(BLIBS)

and my test script:

import sys

# My modules.
import ipg

ipg.test()

The output binary is placed alongside the test script, and the test script is run. This results in the following error:

Traceback (most recent call last): File "test.py", line 4, in import ipg ImportError: No module named ipg

What flags should I be using to compile my output binary, and how should I go about importing it into python? I've used boost.Python on Windows before, but that was quite a while ago.

1 Answer 1

6

On Linux, if your module is called ipg, then you need to be creating a file called ipg.so. Here's a simple makefile;

ipg.o:
    g++ -o ipg.o -c ipg.cc -Wall -fPIC -I/usr/include/python2.7
ipg.so: ipg.o
    g++ -shared -o ipg.so ipg.o -lpython2.7 -lboost_python -lboost_system
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, that was pretty simple, thanks. Could you explain to me why I need the .so on the end? Does Python perform some sort of behind-the-scenes magic beforehand, requiring the extension as a filtering mechanism?
It's just simply part of the lookup mechanism. Depending on the architecture, the importer will look for foo.py (source), foo.pyc (bytecode compiled), foo.pyo (bytecode optimized), foo.pyd (windows extension), foo.so (unix extension), foo.dylib (mac extension). I'm not certain on the ordering.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.