Bojan Nikolic: Numerical and Quantitative Methods in C++

[website home] | [BN Algorithms]

Interfacing with GSL

The Gnu Scientific Library (GSL) contains a large number of useful numerical routines. It is, however, written in the C (rather than C++) programing language, which means that using the functions from C++ is possible but not entirely straightforward if you use many C++ constructs. In this chapter I describe some techniques to make this interfacing easier.

Memory cleanup

Many GSL functions require allocation of memory, either to hold input and output data or for working space for the functions themselves. The GSL memory allocation functions however only return plain C pointers, leaving therefore the responsibility for freeing the memory to the user.

This process of cleaning up the memory can, however, be automatised by using the Boost shared pointer with a custom deleter, as the following example illustrates:

// Bojan Nikolic <bojan@bnikolic.co.uk>
// Illustration of automatic deletion of GSL working space
// structures

#include <boost/shared_ptr.hpp>
#include <gsl/gsl_integration.h>

void worker1(void)
{
  gsl_integration_workspace *w 
    = gsl_integration_workspace_alloc(1000);
  
}

void worker2(void)
{
  // Note the second parameter to the shared pointer constructor is
  // the deleter function
  boost::shared_ptr<gsl_integration_workspace>
    w(gsl_integration_workspace_alloc(1000), 
      gsl_integration_workspace_free);
}

int main(void)
{
  //This would leak memory
  //worker1();
  worker2();
}

Note that to access the memory in the boost::shared_ptr<T> when interfacing to a C-language function, you should use the get() function; in the example above, w.get() would return an object of type gsl_integration_workspace * that can be passed into GSL functions.

Arrays

Instead of using C-style arrays of doubles, you can almost always use std::vector and pass the pointer to the first element of the vector. This is because the elements of std::vector are guaranteed to be contiguous in memory (see for example this blog post).