My goal is to use SWIG with C and Python to create a function that takes a NumPy array as input and returns a different NumPy array. The returned array is of some unspecified size that depends on the input array. Unfortunately when I try to run my code I get an empty array returned. Here is a "minimal" example that shows the problem. I run this code via:
python setup.py build_ext --inplace
python test.py
The files of interest are copied below. Please let me know if you know how to make this code return a nonempty NumPy array. Thanks!
cancelterms.c:
#include "cancelterms.h"
void cancel(double complex* vec, int m, int n, double complex sum[])
{
// Some code that processes vec.
// This is just an example. In practice the following lines will depend on vec.
sum[0] = 1.0;
sum[1] = 2.5;
sum[2] = 3.6;
}
cancelterms.h:
#include <stdlib.h>
#include <stdio.h>
#include <complex.h>
void cancel(double complex* vec, int m, int n, double complex sum[]);
cancelterms.i:
%module cancelterms
%{
/* Put header files here or function declarations like below */
#define SWIG_FILE_WITH_INIT
#include "cancelterms.h"
%}
%include "numpy.i"
%include <complex.i>
%numpy_typemaps(double complex, NPY_CDOUBLE, int)
%init %{
import_array();
%}
%apply (double complex* INPLACE_ARRAY2, int DIM1, int DIM2) {(double complex* vec, int m, int n)}
%apply (double complex ARGOUT_ARRAY1[ANY]) {(double complex sum[])}
%include "cancelterms.h"
setup.py:
# Import necessary modules.
from distutils.core import setup, Extension
import numpy as np
try:
numpy_include = np.get_include()
except AttributeError:
numpy_include = np.get_numpy_include()
example_module = Extension('_cancelterms', sources=['cancelterms.c', 'cancelterms.i'], include_dirs = [numpy_include])
setup(name='cancelterms', ext_modules=[example_module], py_modules=["cancelterms"])
test.py:
import cancelterms
import numpy as np
a=np.array([[1.0j,2.0j,3.0j,4.0j,5.0j,6.0j],[-1.0j,-2.0j,-3.0j,6.0j,7.0j,8.0j]])
print cancelterms.cancel(a)
Unfortunately numpy.i is too large to paste here, but I use the standard numpy.i file from the numpy github repository with the small modification that I add double complex to the list of types.