0

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.

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

This question has been answered several times already

return double * from swig as python list

SWIG C-to-Python Int Array

1 Comment

But the current answers only work for a set array size. I'm interested in variable length arrays.

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.