Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Procedure for building and importing a Boost.python module using GCC?

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.

like image 519
Liam M Avatar asked Oct 28 '25 05:10

Liam M


1 Answers

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
like image 111
Nathan Binkert Avatar answered Oct 29 '25 18:10

Nathan Binkert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!