编程环境Qt5.7.1 MSVC版,VS2013,python3.7.1,我使用Qt像python传递字节数组,Qt和python代码如下,当多次点击按钮多次调用(第二次调用时)python程序时,提示程序异常结束。
Qt程序:
INCLUDEPATH +=D:/Python3.7.3/include
INCLUDEPATH += D:/Python3.7.3/Lib/site-packages/numpy/core/include
LIBS += -LD:/Python3.7.3/libs/ -lpython37
int init_numpy()
{
import_array();
}
void MainWindow::on_ButtonNumpy_clicked()
{
Py_Initialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化
init_numpy();
if (!Py_IsInitialized())
{
printf("初始化失败!");
return ;
}
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");//这一步很重要,修改Python路径
PyObject pModule = PyImport_ImportModule("demo2");//这里是要调用的文件名hello.py
PyObject pDict = PyModule_GetDict(pModule);
if (pModule == NULL)
{
printf("Can't open python file\n");
return ;
}
//PyObject pFunc = PyObject_GetAttrString(pModule, "szSecTest");
double CArrays[3][3] = {{1.3, 2.4, 5.6}, {4.5, 7.8, 8.9}, {1.7, 0.4, 0.8}};
qDebug()<<"rrr";
npy_intp Dims[2] = {3, 3};
//生成包含这个多维数组的PyObject对象,使用PyArray_SimpleNewFromData函数,第一个参数2表示维度,第二个为维度数组Dims,第三个参数指出数组的类型,第四个参数为数组
PyObject PyArray = PyArray_SimpleNewFromData(2, Dims, NPY_DOUBLE, CArrays);
PyObject ArgArray = PyTuple_New(1);
PyTuple_SetItem(ArgArray, 0, PyArray);
PyObject pFunc = PyDict_GetItemString(pDict , "Test");//这里是要调用的函数名
// PyObject * pFunc = PyObject_GetAttrString(pModule , "Test");
if (!pFunc){
printf("Get function hello failed\n");
return ;
} PyObject *pRrturn = PyObject_CallObject(pFunc, ArgArray); qDebug()<<pRrturn; PyArray = NULL; ArgArray = NULL; pRrturn = NULL; pModule=NULL; pDict=NULL; Py_Finalize();
}
python程序:import numpy as np
def Test(test):
print (test.shape,test[0], test[1],test[2])
报错:
Starting F:\Qt\build-TestNumpy-Desktop_Qt_5_7_1_MSVC2013_32bit-Release\release\TestNumpy.exe...
rrr
(3, 3) [1.3 2.4 5.6] [4.5 7.8 8.9] [1.7 0.4 0.8]
0x66937c44
D:\搜狗输入法\SogouInput\Components\程序异常结束。
F:\Qt\build-TestNumpy-Desktop_Qt_5_7_1_MSVC2013_32bit-Release\release\TestNumpy.exe crashed.