天天看点

python import numpy 出错_python - 编译多个模块时,import_array()出现numpy / CAPI错误 - 堆栈内存溢出...

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

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

//pycapi_utils.h

#if ! defined _PYCAPI_UTILS_H

#define _PYCAPI_UTILS_H 1

#include

#include

#include

#include

#include

typedef std::tuple pykeyval; //Tuple type (string,Pyobj*) as dictionary entry (key,val)

typedef std::list 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

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() 。

我一直在寻找这个职位上叠交流,但我无法弄清楚是否以及如何正确定义#define在我的情况的指令。 此外,在该职位的例子不正是我的情况,因为, import_array()是在全球范围内调用main()而在我的情况import_array()被调用我的内simulate是通过调用例程main()通过建立scipy.weave 。