Before recent advances such as Cython, Boost.Python was one of the best ways to integrate C++ code into Python programs. The following C++ source code exposes a C++ function to Python. The function takes a NumPy array as an argument and extracts a C++ integer type.

#include 
#include "boost/python/extract.hpp"
#include "boost/python/numeric.hpp"
#include 

using namespace boost::python;

// Functions to demonstrate extraction
void setArray(boost::python::numeric::array data) {

	// Access a built-in type (an array)
	boost::python::numeric::array a = data;
	// Need to  array elements because their type is unknown
	std::cout << "First array item: " << extract(a[0]) << std::endl;
}


// Expose classes and methods to Python
BOOST_PYTHON_MODULE(TestNumPy) {
	boost::python::numeric::array::set_module_and_type("numpy", "ndarray");
	
	def("setArray", &setArray);

}

2 thoughts on “Boost.python Numpy example

  1. I get this error :

    import TestNumpy as tnp
    ImportError: dynamic module does not define init function (initTestNumpy)

    Like

  2. Hi ,

    I get the error “Segmentation fault: 11”

    when i run the python code after compiling above c++ code

    #————— #

    import TestNumPy as nt
    import numpy as np
    a = np.array([10,20,30])
    nt.setArray(a)

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s