【问题标题】:Numpy/CAPI error with import_array() when compiling multiple modules编译多个模块时 import_array() 的 Numpy/CAPI 错误
【发布时间】:2015-10-02 02:20:08
【问题描述】:

我正在尝试编译一个 C++ 模块以在 scipy.weave 中使用,该模块由多个头文件和源 C++ 文件组成。这些文件包含广泛使用 Numpy/C-API 接口的类和方法。但我无法弄清楚如何成功包含import_array()。在过去的一周里,我一直在为此苦苦挣扎,我快疯了。我希望你能帮我解决这个问题,因为 weave help 不是很解释。

实际上,我首先有一个名为pycapi_utils 的模块,其中包含一些将C 对象与Python 对象接口的例程。它由一个头文件pycapi_utils.h和一个源文件pycapi_utils.cpp组成如:

//pycapi_utils.h
#if ! defined _PYCAPI_UTILS_H
#define _PYCAPI_UTILS_H 1

#include <stdlib.h>
#include <Python.h>
#include <numpy/arrayobject.h>
#include <tuple>
#include <list>

typedef std::tuple<const char*,PyObject*> pykeyval; //Tuple type (string,Pyobj*) as dictionary entry (key,val)
typedef std::list<pykeyval> kvlist;                    

//Declaration of methods
PyObject* array_double_to_pyobj(double* v_c, long int NUMEL); //Convert from array to Python list (double)
...
...
#endif

和

//pycapi_utils.cpp

#include "pycapi_utils.h"

PyObject* array_double_to_pyobj(double* v_c, long int NUMEL){
    //Convert a double array to a Numpy array
    PyObject* out_array = PyArray_SimpleNew(1, &NUMEL, NPY_DOUBLE);
    double* v_b = (double*) ((PyArrayObject*) out_array)->data;
    for (int i=0;i<NUMEL;i++) v_b[i] = v_c[i];
    free(v_c);
    return out_array;
}

然后我还有一个模块model,其中包含处理一些数学模型的类和例程。同样,它由一个头文件和源文件组成,例如:

//model.h
#if ! defined _MODEL_H
#define _MODEL_H 1

//model class
class my_model{
    int i,j;
    public:
        my_model();
        ~my_model();
        double* update(double*); 
}

//Simulator   
PyObject* simulate(double* input);
#endif  

和

//model.cpp

#include "pycapi_utils.h"
#include "model.h"

//Define class and methods
model::model{
...
...
}

...
...

double* model::update(double* input){
    double* x = (double*)calloc(N,sizeof(double));
    ...
    ...

    // Do something
    ...
    ...

    return x;
}

PyObject* simulate(double* input){
    //Initialize Python interface 
    Py_Initialize;
    import_array();

    model random_network;
    double* output;

    output = random_network.update(input);
    return array_double_to_pyobj(output);  // from pycapi_utils.h     
}

以上代码包含在 Python 中的 scipy.weave 模块中

def model_py(input):
    support_code="""
                 #include "model.h"
                 """
    code = """
           return_val = simulate(input.data());
           """
    libs=['gsl','gslcblas','m']
    vars = ['input']
    out = weave.inline(code,
                       vars,
                       support_code=support_code,
                       sources = source_files,
                       libraries=libs
                       type_converters=converters.blitz,
                       compiler='gcc',
                       extra_compile_args=['-std=c++11'],
                       force=1) 

它无法编译给:

error: int _import_array() was not declared in this scope

值得注意的是,如果我将pycapi_utils.h 和源pycapi_utils.cpp 混为一谈,一切正常。但我不想使用这个解决方案,因为实际上我的模块需要包含在其他几个也使用 PyObjects 的模块中,并且需要调用 import_array()。

我在堆栈交换中寻找this post,但我无法弄清楚在我的情况下是否以及如何正确定义#define 指令。此外,该帖子中的示例也不完全是我的情况,import_array() 在main() 的全局范围内被调用,而在我的情况下,import_array() 在我的simulate 例程中被调用,该例程由main() build 调用scipy.weave.

【问题讨论】:

    标签: python c++ c numpy python-c-api


    【解决方案1】:

    我遇到了类似的问题,正如您发布的链接所指出的那样,万恶之源是 PyArray_API 被定义为静态的,这意味着每个翻译单元都有自己的 PyArray_API 初始化为PyArray_API = NULL 默认情况下。因此必须为每个*.cpp 文件调用一次import_array()。在您的情况下,在pycapi_utils.cpp 中调用它就足够了,在model.cpp 中调用一次就足够了。您还可以在实际调用它之前测试是否需要 array_import:

    if(PyArray_API == NULL)
    {
        import_array(); 
    }
    

    【讨论】:

    • 只是偶然发现这个问题的解决方案有据可查here in the numpy documentation
    • 您提供的链接是否提倡使用与您不同的解决方案? 1) import_array 仅在一个文件中,2) 在该文件和其他文件中使用 #define PY_ARRAY_UNIQUE_SYMBOL,3) 在不使用 import_array 的文件中使用 #define NO_IMPORT_ARRAY。
    【解决方案2】:

    显然,如果我在 pycapi_utils 模块中包含一个简单的初始化例程,例如:

    //pycapi_utils.h
    ...
    ...
    void init_numpy();
    
    //pycapi_utils.cpp
    ...
    ...
    void init_numpy(){
        Py_Initialize;
        import_array();
    }
    

    然后我在我的 C 代码中使用 Numpy 对象的任何函数/方法的开头调用此例程,它可以工作。也就是将上面的代码编辑为:

    //pycapi_utils.cpp
    ...
    ...
    PyObject* array_double_to_pyobj(...){
        init_numpy();
        ...
        ...
    }
    
    
    //model.cpp
    ...
    ...
    PyObject* simulate(...){
        init_numpy();
        ...
        ...
    }
    

    此时我唯一关心的是是否有办法最大限度地减少对init_numpy() 的调用次数,或者无论我必须从我在使用 Numpy 对象的 CPP 模块中定义的任何函数中调用它...

    【讨论】:

      猜你喜欢
      • 2015-11-05
      • 2012-11-21
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多