1

I'm trying to wrap some c++ code with python using swig and I need to send NumPy arrays into the c++ vector class for some processing.

My problem is that I don't seem to be able to access "numpy.i" in my swig .i file.

How can I import/include numpy.i?

add_vector.i

%module add_vector
%{
    #define SWIG_FILE_WITH_INIT
    #include "add_vector.h"
%}

%include "numpy.i"

%init %{
import_array();
%}

%include std_vector.i
%template(vecInt) std::vector<int>;

%include "add_vector.h"

Makefile

all:
rm -f *.so *.o *_wrap.* *.pyc *.gch add_vector.py
swig -c++ -python add_vector.i
g++ -O0 -g3 -fpic -c add_vector_wrap.cxx add_vector.h add_vector.cpp -I/home/tools/anaconda3/pkgs/python-3.7.3-h0371630_0/include/python3.7m/
g++ -O0 -g3 -shared add_vector_wrap.o add_vector.o -o _add_vector.so

tester.py

import add_vector as vec 
import numpy as np

a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.empty(len(a))

vec.add(c,a,b)

print('c:', c)

Output:

rm -f *.so *.o *_wrap.* *.pyc *.gch add_vector.py
swig -c++ -python add_vector.i
add_vector.i:7: Error: Unable to find 'numpy.i'
Makefile:2: recipe for target 'all' failed
make: *** [all] Error 1

I'm using debian, in case that matters.

Thanks!

Otherness
  • 385
  • 2
  • 16
  • Where did you put your `numpy.i` file? – user2357112 Oct 19 '19 at 04:22
  • I think you'll want to give up on the Ubuntu packages and just take a source release of numpy straight from their site. – Flexo Oct 24 '19 at 17:54
  • @Flexo I just reinstalled numpy by "conda install -c anaconda numpy" as specified here: https://anaconda.org/anaconda/numpy But this didn't change anything. Still no numpy.i anywhere aside from my python2.7 package. If you have numpy.i on your machine, do you think you could tell me what you see when you type "locate numpy.i"? – Otherness Oct 24 '19 at 18:57
  • @Flexo Solved! See my 2nd comment under Jonathan's answer. – Otherness Oct 24 '19 at 22:26

1 Answers1

2

Copy numpy.i into the same folder as add_vector.i.

Or use the command line option -lifile and give it the path to your numpy.i file.

swig -l/path/to/numpy.i ...

For a list of SWIG command line options, see http://www.swig.org/Doc3.0/SWIGDocumentation.html#SWIG_nn2

Jonathan
  • 694
  • 1
  • 6
  • 13
  • This works to get rid of the error I posted (thanks!), but the only numpy.i file I have comes from a python2.7 package, which doesn't work as it should. I'm not sure why, but numpy.i didn't come in my pyhton3.7.3 package and I can't figure out how to get it. – Otherness Oct 24 '19 at 18:33
  • 1
    Solved: Find which version of numpy you're running, then go here (https://github.com/numpy/numpy/releases) and download the numpy-[your_version].zip file, then specifically copy the numpy.i file, found in numpy-[your_version]/tools/swig/. Now paste that numpy.i into your project working directory. – Otherness Oct 24 '19 at 22:23