将python安装目录下的include和libs文件夹分别包含在VC++目录下,如下图:
code 1:
#include
#include
using namespace std;
int main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("print 'Hello Python!'\n");
Py_Finalize();
return 0;
}
//.cpp调用pyhton .py文件
#include
#include
using namespace std;
int main()
{
Py_Initialize();
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
pModule = PyImport_ImportModule("py_test");
if (!pModule){
cout << "get module failed!" << endl;
exit(0);
}
pFunc = PyObject_GetAttrString(pModule, "Hello");
PyEval_CallObject(pFunc, NULL);
Py_Finalize();
return 0;
}
#py_test.py
def Hello():
print "Hello, Jason"
下面是调用python脚本的一般步骤:
下面code3实例为python脚本带参数:
//python函数带参数
#include
int main()
{
Py_Initialize();
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
PyObject * pArg = NULL;
pModule = PyImport_ImportModule("py_test2_para");
pFunc = PyObject_GetAttrString(pModule, "add");
pArg = Py_BuildValue("(i,i)", 10, 15); //构造一个元组
PyEval_CallObject(pFunc, pArg);
Py_Finalize();
return 0;
}
#py_test_para.py,带参数
def add(a, b):
print "a+b=", a+b
除了上面调用python脚本的方法,还可以使用c++代码中直接嵌入方式,先附一段嵌入的python代码:
/* embedding Python code */
char *pycode =
"from scipy import signal\n"
"def bwlp(order, f, samplingRate):\n"
" b, a = signal.butter(order, f/samplingRate, 'low', analog=False)\n"
" return b, a\n"
"a, b = bwlp(1, f, samplingRate)\n"
"a0 = a[0]\n"
"a1 = a[1]\n"
"b0 = b[0]\n"
"b1 = b[1]\n";
下面使用上面的python代码:
double low_a[2], low_b[2], high_a[2], high_b[2];
// call python butter func
PyObject *main_module, *main_dict;
PyObject *b0_obj, *b1_obj, *a0_obj, *a1_obj, *f_obj, *samplerate_obj;
Py_Initialize();
// 检查初始化是否成功
if ( !Py_IsInitialized() ) {
return -1;
}
/* Setup the __main__ module to use */
main_module = PyImport_ImportModule("__main__");
main_dict = PyModule_GetDict(main_module);
/* C var to Python var */
samplerate_obj = PyInt_FromLong(long(samplingRate));
f_obj = PyFloat_FromDouble(fl);
/* inject var into __main__ */
PyDict_SetItemString(main_dict, "f", f_obj);
PyDict_SetItemString(main_dict, "samplingRate", samplerate_obj);
PyRun_SimpleString(pycode);
/* Extract the resultant var, double a, b */
b0_obj = PyMapping_GetItemString(main_dict, "b0");
a0_obj = PyMapping_GetItemString(main_dict, "a0");
b1_obj = PyMapping_GetItemString(main_dict, "b1");
a1_obj = PyMapping_GetItemString(main_dict, "a1");
low_b[0] = PyFloat_AsDouble(b0_obj);
low_b[1] = PyFloat_AsDouble(b1_obj);
low_a[0] = PyFloat_AsDouble(a0_obj);
low_a[1] = PyFloat_AsDouble(a1_obj);
Py_Finalize();
参考:
http://blog.csdn.net/taiyang1987912/article/details/44779719
https://www.zhihu.com/question/23003213
http://blog.csdn.NET/sunboyiris/article/details/23737915
http://blog.csdn.net/abcjennifer/article/details/49377123