参照如下博客可以看看写好的cpp 在G++中怎么编译:
http://blog.csdn.net/taiyang1987912/article/details/44779719
参考如下博客可以看看怎么在VS的项目中配置调用python接口
http://blog.csdn.net/c_cyoxi/article/details/23978007
参考如下地址可以解决VS中没有Python27_d.lib的问题,本人选择方法2:
http://blog.sina.com.cn/s/blog_75e9551f0101aajd.html
实例运行代码如下:
Cpp代码:
#include <Python.h>
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main()
{
Py_Initialize(); //初始化 python
if (!Py_IsInitialized())
{
cout << "initialized error" << endl;
return -1;
}
PyRun_SimpleString("import sys"); // 执行 python 中的短语句
PyRun_SimpleString("print 'come in python'");
PyRun_SimpleString("sys.path.append('./')");
PyObject *pName(0), *pModule(0), *pDct(0), *pFunc(0), *pArgs(0);
pName = PyString_FromString("pytest"); //载入名为 pytest的脚本
pModule = PyImport_Import(pName);
if (!pModule)
{
cout << "can not find pytest.py" << endl;
return -1;
}
else
cout << "open Module" << endl;
pDct = PyModule_GetDict(pModule);
if (!pDct)
{
cout << "pDct error" << endl;
return -1;
}
pFunc = 0;
pFunc = PyDict_GetItemString(pDct, "add"); //找到名为 add 的函数
if (!pFunc || !PyCallable_Check(pFunc))
{
cout << "pFunc error" << endl;
return -1;
}
pArgs = PyTuple_New(2); //为传入形参开辟空间
//放置传入的形参,类型说明:
//s 字符串 , 均是C 风格的字符串
//i 整型
//f 浮点数
//o 表示一个 python 对象
PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", 1));
PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", 2));
PyObject_CallObject(pFunc, pArgs);
system("pause");
}
pytest.py代码如下:
def add(a,b):
print "come in add"
print a + b