wbinventor
wbinventor

Reputation: 365

How to convert a C++ array to a Python list using SWIG?

I am trying to write a piece of code in C++ which can produce an array and return it as as a Python list. I understand that I can return the list as a NumPy array using the typemaps in numpy.i instead, but NumPy is not installed on some of the clusters I am using. The main difference between this question and some similar ones I've seen on here is that I want to return a C array of variable length as a Python list.

The stripped down C++ routine is below:

/* File get_rand_list.cpp */
#include "get_rand_list.h"

/* Define function implementation */ 
double* get_rand_list(int length) {

  output_list = new double[length];

  /* Populate input NumPy array with random numbers */
  for (int i=0; i < length; i++)
    output_list[i] = ((double) rand()) / RAND_MAX;

  return output_list;
}

I would like to be able to use this in Python as so:

from get_rand_list import *
list = get_rand_list(10)

Which would return a Python list of 10 random floats. How can I use SWIG typemaps to wrap the C++ routine to do this? If there is a simpler way which requires some small modifications to the C++ routine that is most likely fine.

Upvotes: 0

Views: 8680

Answers (2)

Oliver
Oliver

Reputation: 29621

Since you are using C++ it is easiest to use STL: SWIG knows how to convert std::vector to Python list, so use

std::vector<double> get_rand_list(int length) { ... }

Don't forget to %import std_vector.i. This trick is very useful in general, see the Library section of SWIG docs for other typemaps pre-written. Always favor pre-written typemaps over making your own.

Upvotes: 5

Sergii Khaperskov
Sergii Khaperskov

Reputation: 441

This question has been answered several times already

return double * from swig as python list

SWIG C-to-Python Int Array

Upvotes: 1

Related Questions