OS: macOS Sierra 10.12.4
python distribution: Anaconda python 3.6
I'm learning how to pass numpy array to c++ with distutils.
There is an error occured when I run:
$ python setup.py build_ext
error:
sample_wrap.cpp:4571:3: error: use of undeclared identifier 'import_array'
import_array();
^
1 error generated.
file: sample.i
/* file: sample.i */
%module sample
%{
/* include C++ header files necessary to compile the interface */
#include "src/sample.h"
%}
%include "typemaps.i"
%include "src/numpy.i"
%init %{
import_array();
%}
%apply (int DIM1, double* IN_ARRAY1) {(int n, double *a), (int m, double *b)};
%apply (int DIM1, double* ARGOUT_ARRAY1) {(int size, double *arr)};
%include "src/sample.h"
file: setup.py
# ----- file: setup.py -----
from distutils.core import setup, Extension
import numpy
import os
name = "sample" # name of the module
version = "1.0" # the module's version number
os.environ['CC'] = 'g++';
os.environ['CXX'] = 'g++';
setup(name=name, version=version,
ext_modules=[Extension(name='_sample',
sources=["sample.i", "src/sample.cpp"],
include_dirs=['src',numpy.get_include()],
swig_opts=["-c++"]
)]
)
file: src/sample.cpp
/* ----- file: src/sample.cpp ----- */
#include <cmath>
#include "sample.h"
double dot(int n, double *a, int m, double *b){
double sum = 0.0;
for (int i=0; i<n; ++i){
sum += a[i]*b[i];
}
return sum;
}
void arange(int size, double *arr){
for (int i=0; i<size; ++i)
arr[i] = i;
}
file: src/sample.h
/* ----- file: src/sample.h ----- */
#ifndef SAMPLE_H_
#define SAMPLE_H_
double dot(int n, double *a, int m, double *b);
void arange(int size, double *arr);
#endif // SAMPLE_H_
I've tried to change os.environ['CC'] = 'g++'
and os.environ['CXX'] = 'g++'
to os.environ['CC'] = 'g++-6'
and os.environ['CXX'] = 'g++-6'
in setup.py
, in order to compiling with GUN g++ not clang, but still get similar error:
sample_wrap.cpp: In function 'PyObject* PyInit__sample()':
sample_wrap.cpp:4571:16: error: 'import_array' was not declared in this scope
import_array();
^
I would try adding #define SWIG_FILE_WITH_INIT
based on this documentation
/* file: sample.i */
%module sample
%{
#define SWIG_FILE_WITH_INIT
#include "src/sample.h"
%}