天天看點

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 。