1
我想从我的cpp文件调用一个python模块函数。从C++调用Python函数
我已经做了电话如下:
#include <iostream>
#include "Python.h"
int
main(int argc, char** argv)
{
Py_Initialize();
PyObject *pName = PyString_FromString("tmpPyth");
PyObject *pModule = PyImport_Import(pName);
std::cout<< "Works fine till here";
PyObject *pDict = PyModule_GetDict(pModule);
if (pModule != NULL) {
PyObject *pFunc = PyObject_GetAttrString(pDict, "pyFunc");
if(pFunc != NULL){
PyObject_CallObject(pFunc, NULL);
}
}
else
std::cout << "Python Module not found";
return 0;
}
我的Python模块定义如下:
import numpy
import scipy
import matplotlib
from scipy import stats
def blah():
baseline = [9.74219, 10.2226, 8.7469, 8.69791, 9.96442, 9.96472, 9.37913, 9.75004]
follow_up = [9.94227,9.46763,8.53081,9.43679,9.97695,10.4285,10.159,8.86134]
paired_sample = stats.ttest_rel(baseline , follow_up)
print "The t-statistic is %.3f and the p-value is %.3f." % paired_sample
在CPP文件中的代码运行正常,直到第一次“的std :: cout“,但最终给了我一个”seg fault“。单独运行python代码可以正常工作,并提供所需的输出。
我不知道发生了什么问题。任何帮助将不胜感激。 (注意程序编译正确并且运行正确,直到第一个“cout”)
我可以告诉你,那是因为'的PyObject *段错误= pDict PyModule_GetDict(pModule);' 。好像根本无法加载模块。 – vaidik
理想情况下,确保模块已加载后,该行应在if块中。 – vaidik