swig c++ to python (with numpy): error: use of undeclared identifier 'import_array'

Posted

技术标签:

【中文标题】swig c++ to python (with numpy): error: use of undeclared identifier \'import_array\'【英文标题】:swig c++ to python (with numpy): error: use of undeclared identifier 'import_array'swig c++ to python (with numpy): error: use of undeclared identifier 'import_array' 【发布时间】:2017-05-03 02:56:57 【问题描述】:

操作系统:macOS Sierra 10.12.4

python 发行版:Anaconda python 3.6

我正在学习如何使用 distutils 将 numpy 数组传递给 c++。

运行时出现错误:

$ python setup.py build_ext

错误:

sample_wrap.cpp:4571:3: error: use of undeclared identifier 'import_array'
  import_array();
  ^
1 error generated.

文件: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"

文件: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++"]
                           )]
    )

文件: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;

文件: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_

我尝试将setup.py 中的os.environ['CC'] = 'g++'os.environ['CXX'] = 'g++' 更改为os.environ['CC'] = 'g++-6'os.environ['CXX'] = 'g++-6',以便用GUN g++ 编译而不是clang,但仍然得到类似的错误:

sample_wrap.cpp: In function 'PyObject* PyInit__sample()':
sample_wrap.cpp:4571:16: error: 'import_array' was not declared in this scope
   import_array();
                ^

【问题讨论】:

【参考方案1】:

我会尝试根据这个documentation添加#define SWIG_FILE_WITH_INIT

/* file: sample.i */
%module sample
%
#define SWIG_FILE_WITH_INIT
#include "src/sample.h"
%

【讨论】:

以上是关于swig c++ to python (with numpy): error: use of undeclared identifier 'import_array'的主要内容,如果未能解决你的问题,请参考以下文章

SWIG:如何将复数向量从 C++ 传递到 python

使用 SWIG 将 numpy 数组元素(int)传递给 c++ int

swig c++ to perl : 如何使用 c++11 字符串 STL 函数

用 go + swig 替换 c++

SWIG:你能否使用 SWIG 专门使用 C++ 头文件使 C++ 在 Python 中可用?

Swig C++ to C#:如何从 C++ 包装类以使模板类中的方法在 C# 的派生类中可用?